Files
grass-cutters/Assets/Scripts/Net/NetSession.cs
NiemandKG ae558b8e77 Demo build: 150 kg goal, end screen, separate AppId and store assets
GC_DEMO define (ProjectBuilder GC_DEMO=1 / -demo) builds GrassCutterDemo.exe
for app 5668050 with its own product name, version 0.1-demo and no
achievements. Purchases lock after shipping 150 kg; a goal label and a
thanks/wishlist card follow. Menu gets a DEMO badge and wishlist button.
Store texts (12 languages) and DEMO-badged capsules for the demo page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:07:43 +06:00

376 lines
16 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using Steamworks;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using UnityEngine;
namespace GrassCutter
{
public struct LobbyInfo
{
public CSteamID id;
public string name;
public int members, max;
}
/// <summary>
/// Front door for multiplayer: Steam lobbies (create / browse / invite / join from friends list)
/// plus UnityTransport for a solo game, a game on the local network and local multi-instance testing.
/// </summary>
public class NetSession : MonoBehaviour
{
public const string GameKey = "grasscutter";
public const string Version = Demo.On ? "0.1-demo" : "0.1";
public const int MaxPlayers = 16;
const ushort LocalPort = 7777;
public static NetSession Instance { get; private set; }
public enum State { Menu, Connecting, InGame }
public enum LobbyKind { Friends, Invite, Public, Solo, Lan }
public State Current { get; private set; } = State.Menu;
public CSteamID LobbyId { get; private set; } = CSteamID.Nil;
public LobbyKind Kind { get; private set; }
public bool InLobby => LobbyId.IsValid() && LobbyId != CSteamID.Nil;
/// <summary>The port a LAN game listens on, for the pause screen to show.</summary>
public ushort LanPort { get; private set; }
public event Action<string> StatusChanged;
public event Action<string> Failed;
/// <summary>Steam wants to join another of our lobbies while a game is on: the UI asks.</summary>
public event Action<CSteamID> JoinAsked;
public event Action<List<LobbyInfo>> LobbyListReceived;
public event Action Started;
public event Action Ended;
NetworkManager _nm;
SteamSocketsTransport _steamTransport;
UnityTransport _utp;
Callback<LobbyCreated_t> _lobbyCreated;
Callback<LobbyEnter_t> _lobbyEnter;
Callback<LobbyDataUpdate_t> _lobbyData;
CSteamID _asked = CSteamID.Nil;
Callback<GameLobbyJoinRequested_t> _joinRequested;
Callback<LobbyMatchList_t> _lobbyList;
Callback<GameRichPresenceJoinRequested_t> _richJoin;
bool _leaving;
void Awake()
{
Instance = this;
_nm = GetComponent<NetworkManager>();
_steamTransport = GetComponent<SteamSocketsTransport>();
_utp = GetComponent<UnityTransport>();
}
void Start()
{
_nm.ConnectionApprovalCallback = Approve;
_nm.OnClientDisconnectCallback += OnClientDisconnect;
_nm.OnClientConnectedCallback += OnClientConnected;
if (SteamManager.Initialized)
{
_lobbyCreated = Callback<LobbyCreated_t>.Create(OnLobbyCreated);
_lobbyEnter = Callback<LobbyEnter_t>.Create(OnLobbyEnter);
_joinRequested = Callback<GameLobbyJoinRequested_t>.Create(e => AskToJoin(e.m_steamIDLobby));
_lobbyData = Callback<LobbyDataUpdate_t>.Create(OnLobbyData);
_lobbyList = Callback<LobbyMatchList_t>.Create(OnLobbyList);
_richJoin = Callback<GameRichPresenceJoinRequested_t>.Create(e => ParseConnectString(e.m_rgchConnect));
SteamManager.SetRichPresence("In the main menu");
}
// Launched via "Join game" from the Steam friends list while the game was closed.
var arg = CommandLine.Get("+connect_lobby");
if (!string.IsNullOrEmpty(arg) && ulong.TryParse(arg, out ulong lobby)) JoinLobby(new CSteamID(lobby));
else if (CommandLine.Has("-localhost")) HostLocal();
else if (CommandLine.Get("-connect") is string addr && ParseAddress(addr, out var ip, out var port)) JoinLocal(ip, port);
}
void ParseConnectString(string s)
{
if (string.IsNullOrEmpty(s)) return;
var parts = s.Split(' ');
for (int i = 0; i < parts.Length - 1; i++)
if (parts[i] == "+connect_lobby" && ulong.TryParse(parts[i + 1], out ulong id)) AskToJoin(new CSteamID(id));
}
// ───────────────────────── hosting ─────────────────────────
public void Host(LobbyKind kind)
{
if (Current != State.Menu) return;
Kind = kind;
if (kind == LobbyKind.Lan) { HostLan(); return; }
if (kind == LobbyKind.Solo || !SteamManager.Initialized) { Kind = LobbyKind.Solo; HostSolo(); return; }
SetState(State.Connecting, Loc.Pack("Creating lobby…"));
SteamMatchmaking.CreateLobby(kind == LobbyKind.Public ? ELobbyType.k_ELobbyTypePublic : kind == LobbyKind.Invite ? ELobbyType.k_ELobbyTypePrivate : ELobbyType.k_ELobbyTypeFriendsOnly, MaxPlayers);
}
void OnLobbyCreated(LobbyCreated_t e)
{
if (e.m_eResult != EResult.k_EResultOK)
{
Fail(Loc.Pack("Couldn't create a Steam lobby ({0})", e.m_eResult.ToString()));
return;
}
LobbyId = new CSteamID(e.m_ulSteamIDLobby);
SteamMatchmaking.SetLobbyData(LobbyId, "game", GameKey);
SteamMatchmaking.SetLobbyData(LobbyId, "ver", Version);
SteamMatchmaking.SetLobbyData(LobbyId, "name", SteamManager.MyName + "'s Mow Base");
SteamMatchmaking.SetLobbyData(LobbyId, "host", SteamManager.MySteamId.m_SteamID.ToString());
SteamMatchmaking.SetLobbyJoinable(LobbyId, true);
UseTransport(_steamTransport);
if (!_nm.StartHost()) { Fail(Loc.Pack("Failed to start host")); return; }
SteamManager.SetRichPresence("Mowing an overgrown planet", "+connect_lobby " + LobbyId.m_SteamID);
EnterGame();
}
/// <summary>Nobody else can come in: the server listens on this PC only, on whatever port is free.</summary>
void HostSolo()
{
SetState(State.Connecting, Loc.Pack("Starting…"));
UseTransport(_utp);
_utp.SetConnectionData("127.0.0.1", LanBeacon.FreePort(LocalPort), "127.0.0.1");
if (!_nm.StartHost()) { Fail(Loc.Pack("Failed to start the game")); return; }
EnterGame();
}
/// <summary>Open to the local network, and announced on it so the game browser on other PCs lists it.</summary>
void HostLan()
{
SetState(State.Connecting, Loc.Pack("Starting a LAN game…"));
UseTransport(_utp);
LanPort = LanBeacon.FreePort(LocalPort);
_utp.SetConnectionData("127.0.0.1", LanPort, "0.0.0.0");
if (!_nm.StartHost()) { Fail(Loc.Pack("Failed to start a LAN game (port {0})", LanPort.ToString())); return; }
LanBeacon.Host(SteamManager.MyName + "'s Mow Base", LanPort);
EnterGame();
}
void Update()
{
if (LanBeacon.Hosting && Current == State.InGame) LanBeacon.Tick(_nm.ConnectedClientsIds.Count, MaxPlayers);
else LanBeacon.Tick(0, MaxPlayers);
}
/// <summary>Test runs: -localhost hosts on port 7777 for -connect instances on the same PC.</summary>
public void HostLocal()
{
if (Current != State.Menu) return;
SetState(State.Connecting, Loc.Pack("Starting…"));
UseTransport(_utp);
// a dev bot started while someone plays on this PC takes the next free port instead of failing (or -port N)
_utp.SetConnectionData("127.0.0.1", ushort.TryParse(CommandLine.Get("-port"), out var port) ? port : CommandLine.Has("-autodemo") ? LanBeacon.FreePort(LocalPort) : LocalPort, "0.0.0.0");
if (!_nm.StartHost()) { Fail(Loc.Pack("Failed to start host")); return; }
EnterGame();
}
// ───────────────────────── joining ─────────────────────────
/// <summary>
/// Steam was asked to join a lobby. In the menu that just happens. In a game, whoever is playing is asked first, and
/// only about our own lobbies: on the shared test AppID an invite can come from any other game.
/// </summary>
void AskToJoin(CSteamID lobby)
{
if (CommandLine.Has("-autodemo")) return;
if (Current != State.InGame) { JoinLobby(lobby); return; }
if (lobby == LobbyId) return;
_asked = lobby;
SteamMatchmaking.RequestLobbyData(lobby);
}
void OnLobbyData(LobbyDataUpdate_t e)
{
if (e.m_ulSteamIDLobby != _asked.m_SteamID || e.m_ulSteamIDMember != e.m_ulSteamIDLobby) return;
var lobby = _asked;
_asked = CSteamID.Nil;
if (e.m_bSuccess != 0 && SteamMatchmaking.GetLobbyData(lobby, "game") == GameKey) JoinAsked?.Invoke(lobby);
else Failed?.Invoke(Loc.Pack("That invite isn't for a Grass Cutters Together game"));
}
public void JoinLobby(CSteamID lobby)
{
if (!SteamManager.Initialized) return;
if (Current == State.InGame) Leave();
if (Current == State.Connecting) return;
SetState(State.Connecting, Loc.Pack("Joining lobby…"));
SteamMatchmaking.JoinLobby(lobby);
}
void OnLobbyEnter(LobbyEnter_t e)
{
var lobby = new CSteamID(e.m_ulSteamIDLobby);
// The host also receives LobbyEnter for its own lobby — ignore that one.
if (_nm.IsHost && lobby == LobbyId) return;
if (e.m_EChatRoomEnterResponse != (uint)EChatRoomEnterResponse.k_EChatRoomEnterResponseSuccess)
{
Fail(Loc.Pack("Couldn't join the lobby (it may be full or closed)"));
return;
}
if (SteamMatchmaking.GetLobbyData(lobby, "game") != GameKey)
{
SteamMatchmaking.LeaveLobby(lobby);
Fail(Loc.Pack("That lobby isn't a Grass Cutters Together game"));
return;
}
LobbyId = lobby;
var owner = SteamMatchmaking.GetLobbyOwner(lobby);
if (owner == SteamManager.MySteamId) { Fail(Loc.Pack("You are the owner of this lobby")); return; }
_steamTransport.ConnectToSteamId = owner.m_SteamID;
UseTransport(_steamTransport);
SetState(State.Connecting, Loc.Pack("Connecting to {0}…", SteamFriends.GetFriendPersonaName(owner)));
_nm.NetworkConfig.ConnectionData = Encoding.UTF8.GetBytes(Version);
if (!_nm.StartClient()) Fail(Loc.Pack("Failed to start client"));
}
/// <summary>"192.168.1.20" or "192.168.1.20:7778": a LAN game, by address.</summary>
public static bool ParseAddress(string text, out string ip, out ushort port)
{
ip = null; port = LocalPort;
if (string.IsNullOrWhiteSpace(text)) return false;
text = text.Trim();
int colon = text.LastIndexOf(':');
if (colon > 0)
{
if (!ushort.TryParse(text.Substring(colon + 1), out port) || port == 0) return false;
text = text.Substring(0, colon);
}
if (!System.Net.IPAddress.TryParse(text, out var addr) || addr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) return false;
ip = addr.ToString();
return true;
}
public void JoinLocal(string ip, ushort port = LocalPort)
{
if (Current != State.Menu) return;
SetState(State.Connecting, Loc.Pack("Connecting to {0}…", ip + (port == LocalPort ? "" : ":" + port)));
UseTransport(_utp);
Kind = LobbyKind.Lan;
_utp.SetConnectionData(ip, port);
_nm.NetworkConfig.ConnectionData = Encoding.UTF8.GetBytes(Version);
if (!_nm.StartClient()) Fail(Loc.Pack("Failed to start client"));
}
public void RequestLobbyList()
{
if (!SteamManager.Initialized) { LobbyListReceived?.Invoke(new List<LobbyInfo>()); return; }
SteamMatchmaking.AddRequestLobbyListStringFilter("game", GameKey, ELobbyComparison.k_ELobbyComparisonEqual);
SteamMatchmaking.AddRequestLobbyListFilterSlotsAvailable(1);
SteamMatchmaking.AddRequestLobbyListDistanceFilter(ELobbyDistanceFilter.k_ELobbyDistanceFilterWorldwide);
SteamMatchmaking.AddRequestLobbyListResultCountFilter(50);
SteamMatchmaking.RequestLobbyList();
}
void OnLobbyList(LobbyMatchList_t e)
{
var list = new List<LobbyInfo>();
for (int i = 0; i < e.m_nLobbiesMatching; i++)
{
var id = SteamMatchmaking.GetLobbyByIndex(i);
if (SteamMatchmaking.GetLobbyData(id, "ver") != Version) continue;
list.Add(new LobbyInfo
{
id = id,
name = SteamMatchmaking.GetLobbyData(id, "name"),
members = SteamMatchmaking.GetNumLobbyMembers(id),
max = SteamMatchmaking.GetLobbyMemberLimit(id),
});
}
LobbyListReceived?.Invoke(list);
}
public void InviteFriends()
{
if (SteamManager.Initialized && InLobby) SteamFriends.ActivateGameOverlayInviteDialog(LobbyId);
}
// ───────────────────────── lifecycle ─────────────────────────
void UseTransport(NetworkTransport t) => _nm.NetworkConfig.NetworkTransport = t;
void Approve(NetworkManager.ConnectionApprovalRequest req, NetworkManager.ConnectionApprovalResponse res)
{
bool isHostSelf = req.ClientNetworkId == NetworkManager.ServerClientId;
string ver = req.Payload != null && req.Payload.Length > 0 ? Encoding.UTF8.GetString(req.Payload) : "";
bool full = _nm.ConnectedClientsIds.Count >= MaxPlayers;
res.Approved = isHostSelf || (!full && ver == Version);
res.Reason = full ? Loc.Pack("The depot is full") : Loc.Pack("Version mismatch");
res.CreatePlayerObject = true;
res.Pending = false;
}
void OnClientConnected(ulong id)
{
if (!_nm.IsServer && id == _nm.LocalClientId) EnterGame();
}
void OnClientDisconnect(ulong id)
{
if (_leaving) return;
// We (a client) were disconnected from the host.
if (!_nm.IsServer && (id == _nm.LocalClientId || id == NetworkManager.ServerClientId))
{
string reason = string.IsNullOrEmpty(_nm.DisconnectReason) ? Loc.Pack("Lost connection to the host") : _nm.DisconnectReason;
Leave(reason);
}
}
void EnterGame()
{
SetState(State.InGame, "");
if (!SteamManager.Initialized || !InLobby) SteamManager.SetRichPresence("Mowing an overgrown planet");
Started?.Invoke();
}
public void Leave(string reason = null)
{
if (Current == State.Menu && !_nm.IsListening) return;
_leaving = true;
try
{
if (_nm.IsServer && TeamState.Instance) TeamState.Instance.Save();
if (_nm.IsListening) _nm.Shutdown();
LanBeacon.Stop();
if (SteamManager.Initialized && InLobby) SteamMatchmaking.LeaveLobby(LobbyId);
LobbyId = CSteamID.Nil;
SteamManager.SetRichPresence("In the main menu");
}
finally { _leaving = false; }
SetState(State.Menu, "");
Ended?.Invoke();
if (!string.IsNullOrEmpty(reason)) Failed?.Invoke(reason);
}
void Fail(string msg)
{
Debug.LogWarning("[Net] " + msg);
if (_nm.IsListening) _nm.Shutdown();
LanBeacon.Stop();
if (SteamManager.Initialized && InLobby) SteamMatchmaking.LeaveLobby(LobbyId);
LobbyId = CSteamID.Nil;
SetState(State.Menu, "");
Failed?.Invoke(msg);
}
void SetState(State s, string status)
{
Current = s;
StatusChanged?.Invoke(status);
}
void OnApplicationQuit()
{
LanBeacon.Stop();
LanBeacon.StopListening();
if (SteamManager.Initialized && InLobby) SteamMatchmaking.LeaveLobby(LobbyId);
}
}
}