Files
grass-cutters/Assets/Scripts/Net/SteamSocketsTransport.cs
NiemandKG d1c3761e58 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>
2026-11-06 18:44:40 +06:00

274 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Steamworks;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Netcode for GameObjects transport over Steam Networking Sockets (P2P through Valve's relay).
/// The host listens on virtual port 0; clients connect to the host's SteamID.
/// </summary>
public class SteamSocketsTransport : NetworkTransport
{
const int MaxMessagesPerPoll = 256;
public ulong ConnectToSteamId;
struct Pending
{
public NetworkEvent type;
public ulong clientId;
public byte[] data;
public int length;
}
readonly Queue<Pending> _events = new Queue<Pending>();
readonly Dictionary<ulong, HSteamNetConnection> _byClient = new Dictionary<ulong, HSteamNetConnection>();
readonly Dictionary<uint, ulong> _byConn = new Dictionary<uint, ulong>();
readonly IntPtr[] _msgPtrs = new IntPtr[MaxMessagesPerPoll];
Callback<SteamNetConnectionStatusChangedCallback_t> _statusCb;
HSteamListenSocket _listen = HSteamListenSocket.Invalid;
HSteamNetPollGroup _pollGroup = HSteamNetPollGroup.Invalid;
HSteamNetConnection _serverConn = HSteamNetConnection.Invalid;
bool _isServer, _running;
ulong _nextClientId = 1;
IntPtr _sendPtr;
int _sendPtrSize;
public override ulong ServerClientId => 0;
public override bool IsSupported => SteamManager.Initialized;
public override void Initialize(NetworkManager networkManager = null)
{
if (!SteamManager.Initialized) Debug.LogError("[SteamTransport] Steam is not initialized.");
}
public override bool StartServer()
{
if (!SteamManager.Initialized) return false;
_isServer = true;
_running = true;
_statusCb ??= Callback<SteamNetConnectionStatusChangedCallback_t>.Create(OnStatus);
_listen = SteamNetworkingSockets.CreateListenSocketP2P(0, 0, null);
_pollGroup = SteamNetworkingSockets.CreatePollGroup();
Debug.Log("[SteamTransport] Listening for P2P connections");
return _listen != HSteamListenSocket.Invalid;
}
public override bool StartClient()
{
if (!SteamManager.Initialized || ConnectToSteamId == 0) return false;
_isServer = false;
_running = true;
_statusCb ??= Callback<SteamNetConnectionStatusChangedCallback_t>.Create(OnStatus);
var identity = new SteamNetworkingIdentity();
identity.SetSteamID(new CSteamID(ConnectToSteamId));
_serverConn = SteamNetworkingSockets.ConnectP2P(ref identity, 0, 0, null);
Debug.Log($"[SteamTransport] Connecting to {ConnectToSteamId}");
return _serverConn != HSteamNetConnection.Invalid;
}
void OnStatus(SteamNetConnectionStatusChangedCallback_t cb)
{
if (!_running) return;
var conn = cb.m_hConn;
var state = cb.m_info.m_eState;
switch (state)
{
case ESteamNetworkingConnectionState.k_ESteamNetworkingConnectionState_Connecting:
if (_isServer && cb.m_info.m_hListenSocket != HSteamListenSocket.Invalid)
{
var r = SteamNetworkingSockets.AcceptConnection(conn);
if (r != EResult.k_EResultOK)
{
Debug.LogWarning($"[SteamTransport] Accept failed: {r}");
SteamNetworkingSockets.CloseConnection(conn, 0, "accept failed", false);
}
}
break;
case ESteamNetworkingConnectionState.k_ESteamNetworkingConnectionState_Connected:
if (_isServer)
{
ulong id = _nextClientId++;
_byClient[id] = conn;
_byConn[conn.m_HSteamNetConnection] = id;
SteamNetworkingSockets.SetConnectionPollGroup(conn, _pollGroup);
Enqueue(NetworkEvent.Connect, id);
Debug.Log($"[SteamTransport] Client {id} connected ({cb.m_info.m_identityRemote.GetSteamID()})");
}
else
{
Enqueue(NetworkEvent.Connect, ServerClientId);
Debug.Log("[SteamTransport] Connected to host");
}
break;
case ESteamNetworkingConnectionState.k_ESteamNetworkingConnectionState_ClosedByPeer:
case ESteamNetworkingConnectionState.k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
Debug.Log($"[SteamTransport] Connection closed: {state} {cb.m_info.m_szEndDebug}");
if (_isServer)
{
if (_byConn.TryGetValue(conn.m_HSteamNetConnection, out ulong cid))
{
_byConn.Remove(conn.m_HSteamNetConnection);
_byClient.Remove(cid);
Enqueue(NetworkEvent.Disconnect, cid);
}
}
else if (conn == _serverConn)
{
_serverConn = HSteamNetConnection.Invalid;
Enqueue(NetworkEvent.Disconnect, ServerClientId);
}
SteamNetworkingSockets.CloseConnection(conn, 0, "closed", false);
break;
}
}
void Enqueue(NetworkEvent type, ulong clientId, byte[] data = null, int length = 0)
{
_events.Enqueue(new Pending { type = type, clientId = clientId, data = data, length = length });
}
public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment<byte> payload, out float receiveTime)
{
receiveTime = Time.realtimeSinceStartup;
if (_events.Count == 0) PumpMessages();
if (_events.Count > 0)
{
var e = _events.Dequeue();
clientId = e.clientId;
payload = e.data != null ? new ArraySegment<byte>(e.data, 0, e.length) : default;
return e.type;
}
clientId = 0;
payload = default;
return NetworkEvent.Nothing;
}
void PumpMessages()
{
if (!_running) return;
int count;
if (_isServer)
{
if (_pollGroup == HSteamNetPollGroup.Invalid) return;
count = SteamNetworkingSockets.ReceiveMessagesOnPollGroup(_pollGroup, _msgPtrs, MaxMessagesPerPoll);
}
else
{
if (_serverConn == HSteamNetConnection.Invalid) return;
count = SteamNetworkingSockets.ReceiveMessagesOnConnection(_serverConn, _msgPtrs, MaxMessagesPerPoll);
}
for (int i = 0; i < count; i++)
{
var msg = SteamNetworkingMessage_t.FromIntPtr(_msgPtrs[i]);
ulong cid = ServerClientId;
if (_isServer && !_byConn.TryGetValue(msg.m_conn.m_HSteamNetConnection, out cid))
{
SteamNetworkingMessage_t.Release(_msgPtrs[i]);
continue;
}
int size = msg.m_cbSize;
// Each queued message needs its own buffer because several can be queued before NGO consumes them.
var buf = new byte[size];
Marshal.Copy(msg.m_pData, buf, 0, size);
SteamNetworkingMessage_t.Release(_msgPtrs[i]);
Enqueue(NetworkEvent.Data, cid, buf, size);
}
}
public override void Send(ulong clientId, ArraySegment<byte> payload, NetworkDelivery delivery)
{
HSteamNetConnection conn;
if (_isServer)
{
if (!_byClient.TryGetValue(clientId, out conn)) return;
}
else conn = _serverConn;
if (conn == HSteamNetConnection.Invalid) return;
int flags = delivery switch
{
NetworkDelivery.Unreliable => Constants.k_nSteamNetworkingSend_UnreliableNoNagle,
NetworkDelivery.UnreliableSequenced => Constants.k_nSteamNetworkingSend_UnreliableNoNagle,
_ => Constants.k_nSteamNetworkingSend_ReliableNoNagle,
};
int len = payload.Count;
if (_sendPtrSize < len)
{
if (_sendPtr != IntPtr.Zero) Marshal.FreeHGlobal(_sendPtr);
_sendPtrSize = Mathf.NextPowerOfTwo(Mathf.Max(len, 1024));
_sendPtr = Marshal.AllocHGlobal(_sendPtrSize);
}
Marshal.Copy(payload.Array, payload.Offset, _sendPtr, len);
var res = SteamNetworkingSockets.SendMessageToConnection(conn, _sendPtr, (uint)len, flags, out _);
if (res != EResult.k_EResultOK && res != EResult.k_EResultNoConnection)
Debug.LogWarning($"[SteamTransport] Send failed: {res} ({len} bytes)");
}
public override ulong GetCurrentRtt(ulong clientId)
{
HSteamNetConnection conn = _isServer ? (_byClient.TryGetValue(clientId, out var c) ? c : HSteamNetConnection.Invalid) : _serverConn;
if (conn == HSteamNetConnection.Invalid) return 0;
var status = new SteamNetConnectionRealTimeStatus_t();
var lanes = new SteamNetConnectionRealTimeLaneStatus_t();
if (SteamNetworkingSockets.GetConnectionRealTimeStatus(conn, ref status, 0, ref lanes) == EResult.k_EResultOK)
return (ulong)Mathf.Max(0, status.m_nPing);
return 0;
}
public override void DisconnectRemoteClient(ulong clientId)
{
if (_byClient.TryGetValue(clientId, out var conn))
{
SteamNetworkingSockets.CloseConnection(conn, 0, "kicked", true);
_byClient.Remove(clientId);
_byConn.Remove(conn.m_HSteamNetConnection);
}
}
public override void DisconnectLocalClient()
{
if (_serverConn != HSteamNetConnection.Invalid)
{
SteamNetworkingSockets.CloseConnection(_serverConn, 0, "leaving", true);
_serverConn = HSteamNetConnection.Invalid;
}
}
public override void Shutdown()
{
if (!_running) return;
_running = false;
if (SteamManager.Initialized)
{
foreach (var c in _byClient.Values) SteamNetworkingSockets.CloseConnection(c, 0, "shutdown", false);
if (_serverConn != HSteamNetConnection.Invalid) SteamNetworkingSockets.CloseConnection(_serverConn, 0, "shutdown", false);
if (_listen != HSteamListenSocket.Invalid) SteamNetworkingSockets.CloseListenSocket(_listen);
if (_pollGroup != HSteamNetPollGroup.Invalid) SteamNetworkingSockets.DestroyPollGroup(_pollGroup);
}
_byClient.Clear();
_byConn.Clear();
_events.Clear();
_listen = HSteamListenSocket.Invalid;
_pollGroup = HSteamNetPollGroup.Invalid;
_serverConn = HSteamNetConnection.Invalid;
_nextClientId = 1;
}
void OnDestroy()
{
if (_sendPtr != IntPtr.Zero) { Marshal.FreeHGlobal(_sendPtr); _sendPtr = IntPtr.Zero; }
}
}
}