optimizing network stuff

This commit is contained in:
2025-07-30 05:51:39 +02:00
parent ea99249fe2
commit 159e9adcd7
56 changed files with 2272 additions and 1781 deletions

View File

@@ -1,277 +0,0 @@
// Source: https://github.com/Unity-Technologies/multiplayer-community-contributions/blob/main/Transports/com.community.netcode.transport.facepunch/Runtime/FacepunchTransport.cs
using System;
using System.Collections;
using System.Collections.Generic;
using Steamworks;
using Steamworks.Data;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Netcode;
using UnityEngine;
namespace RebootKit.Engine.Steam {
using SocketConnection = Connection;
public class FacepunchTransport : NetworkTransport, IConnectionManager, ISocketManager {
private ConnectionManager connectionManager;
private SocketManager socketManager;
private Dictionary<ulong, Client> connectedClients;
[Space]
[Tooltip("The Steam App ID of your game. Technically you're not allowed to use 480, but Valve doesn't do anything about it so it's fine for testing purposes.")]
[SerializeField] private uint steamAppId = 480;
[Tooltip("The Steam ID of the user targeted when joining as a client.")]
[SerializeField] public ulong targetSteamId;
[Header("Info")]
[ReadOnly]
[Tooltip("When in play mode, this will display your Steam ID.")]
[SerializeField] private ulong userSteamId;
private LogLevel LogLevel => NetworkManager.Singleton.LogLevel;
private class Client {
public SteamId steamId;
public SocketConnection connection;
}
// #region MonoBehaviour Messages
//
// private void Awake() {
// try {
// SteamClient.Init(steamAppId, false);
// } catch (Exception e) {
// if (LogLevel <= LogLevel.Error)
// Debug.LogError($"[{nameof(FacepunchTransport)}] - Caught an exeption during initialization of Steam client: {e}");
// } finally {
// StartCoroutine(InitSteamworks());
// }
// }
//
// private void Update() {
// SteamClient.RunCallbacks();
// }
//
// private void OnDestroy() {
// SteamClient.Shutdown();
// }
//
// #endregion
#region NetworkTransport Overrides
public override ulong ServerClientId => 0;
public override void DisconnectLocalClient() {
connectionManager?.Connection.Close();
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Disconnecting local client.");
}
public override void DisconnectRemoteClient(ulong clientId) {
if (connectedClients.TryGetValue(clientId, out Client user)) {
// Flush any pending messages before closing the connection
user.connection.Flush();
user.connection.Close();
connectedClients.Remove(clientId);
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Disconnecting remote client with ID {clientId}.");
} else if (LogLevel <= LogLevel.Normal)
Debug.LogWarning($"[{nameof(FacepunchTransport)}] - Failed to disconnect remote client with ID {clientId}, client not connected.");
}
public override unsafe ulong GetCurrentRtt(ulong clientId) {
return 0;
}
public override void Initialize(NetworkManager networkManager = null) {
connectedClients = new Dictionary<ulong, Client>();
}
private SendType NetworkDeliveryToSendType(NetworkDelivery delivery) {
return delivery switch {
NetworkDelivery.Reliable => SendType.Reliable,
NetworkDelivery.ReliableFragmentedSequenced => SendType.Reliable,
NetworkDelivery.ReliableSequenced => SendType.Reliable,
NetworkDelivery.Unreliable => SendType.Unreliable,
NetworkDelivery.UnreliableSequenced => SendType.Unreliable,
_ => SendType.Reliable
};
}
public override void Shutdown() {
try {
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Shutting down.");
connectionManager?.Close();
socketManager?.Close();
} catch (Exception e) {
if (LogLevel <= LogLevel.Error)
Debug.LogError($"[{nameof(FacepunchTransport)}] - Caught an exception while shutting down: {e}");
}
}
public override void Send(ulong clientId, ArraySegment<byte> data, NetworkDelivery delivery) {
var sendType = NetworkDeliveryToSendType(delivery);
if (clientId == ServerClientId)
connectionManager.Connection.SendMessage(data.Array, data.Offset, data.Count, sendType);
else if (connectedClients.TryGetValue(clientId, out Client user))
user.connection.SendMessage(data.Array, data.Offset, data.Count, sendType);
else if (LogLevel <= LogLevel.Normal)
Debug.LogWarning($"[{nameof(FacepunchTransport)}] - Failed to send packet to remote client with ID {clientId}, client not connected.");
}
public override NetworkEvent PollEvent(out ulong clientId,
out ArraySegment<byte> payload,
out float receiveTime) {
connectionManager?.Receive();
socketManager?.Receive();
clientId = 0;
receiveTime = Time.realtimeSinceStartup;
payload = default;
return NetworkEvent.Nothing;
}
public override bool StartClient() {
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Starting as client.");
connectionManager = SteamNetworkingSockets.ConnectRelay<ConnectionManager>(targetSteamId);
connectionManager.Interface = this;
return true;
}
public override bool StartServer() {
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Starting as server.");
socketManager = SteamNetworkingSockets.CreateRelaySocket<SocketManager>();
socketManager.Interface = this;
return true;
}
#endregion
#region ConnectionManager Implementation
private byte[] payloadCache = new byte[4096];
private void EnsurePayloadCapacity(int size) {
if (payloadCache.Length >= size)
return;
payloadCache = new byte[Math.Max(payloadCache.Length * 2, size)];
}
void IConnectionManager.OnConnecting(ConnectionInfo info) {
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Connecting with Steam user {info.Identity.SteamId}.");
}
void IConnectionManager.OnConnected(ConnectionInfo info) {
InvokeOnTransportEvent(NetworkEvent.Connect, ServerClientId, default, Time.realtimeSinceStartup);
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Connected with Steam user {info.Identity.SteamId}.");
}
void IConnectionManager.OnDisconnected(ConnectionInfo info) {
InvokeOnTransportEvent(NetworkEvent.Disconnect, ServerClientId, default, Time.realtimeSinceStartup);
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Disconnected Steam user {info.Identity.SteamId}.");
}
unsafe void IConnectionManager.OnMessage(IntPtr data, int size, long messageNum, long recvTime, int channel) {
EnsurePayloadCapacity(size);
fixed (byte* payload = payloadCache) {
UnsafeUtility.MemCpy(payload, (byte*) data, size);
}
InvokeOnTransportEvent(NetworkEvent.Data, ServerClientId, new ArraySegment<byte>(payloadCache, 0, size),
Time.realtimeSinceStartup);
}
#endregion
#region SocketManager Implementation
void ISocketManager.OnConnecting(SocketConnection connection, ConnectionInfo info) {
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Accepting connection from Steam user {info.Identity.SteamId}.");
connection.Accept();
}
void ISocketManager.OnConnected(SocketConnection connection, ConnectionInfo info) {
if (!connectedClients.ContainsKey(connection.Id)) {
connectedClients.Add(connection.Id, new Client() {
connection = connection,
steamId = info.Identity.SteamId
});
InvokeOnTransportEvent(NetworkEvent.Connect, connection.Id, default, Time.realtimeSinceStartup);
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Connected with Steam user {info.Identity.SteamId}.");
} else if (LogLevel <= LogLevel.Normal)
Debug.LogWarning($"[{nameof(FacepunchTransport)}] - Failed to connect client with ID {connection.Id}, client already connected.");
}
void ISocketManager.OnDisconnected(SocketConnection connection, ConnectionInfo info) {
if (connectedClients.Remove(connection.Id)) {
InvokeOnTransportEvent(NetworkEvent.Disconnect, connection.Id, default, Time.realtimeSinceStartup);
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Disconnected Steam user {info.Identity.SteamId}");
} else if (LogLevel <= LogLevel.Normal)
Debug.LogWarning($"[{nameof(FacepunchTransport)}] - Failed to diconnect client with ID {connection.Id}, client not connected.");
}
unsafe void ISocketManager.OnMessage(SocketConnection connection,
NetIdentity identity,
IntPtr data,
int size,
long messageNum,
long recvTime,
int channel) {
EnsurePayloadCapacity(size);
fixed (byte* payload = payloadCache) {
UnsafeUtility.MemCpy(payload, (byte*) data, size);
}
InvokeOnTransportEvent(NetworkEvent.Data, connection.Id, new ArraySegment<byte>(payloadCache, 0, size),
Time.realtimeSinceStartup);
}
#endregion
#region Utility Methods
private IEnumerator InitSteamworks() {
yield return new WaitUntil(() => SteamClient.IsValid);
SteamNetworkingUtils.InitRelayNetworkAccess();
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Initialized access to Steam Relay Network.");
userSteamId = SteamClient.SteamId;
if (LogLevel <= LogLevel.Developer)
Debug.Log($"[{nameof(FacepunchTransport)}] - Fetched user Steam ID.");
}
#endregion
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 516179f3a4a7476ea24875d52fae3042
timeCreated: 1751378412

View File

@@ -51,6 +51,10 @@ namespace RebootKit.Engine.Steam {
s_Logger.Warning("Join request key is empty. Cannot process join request.");
return;
}
if (ulong.TryParse(key, out ulong steamID)) {
RR.ConnectWithSteamID(steamID);
}
}
}
}

View File

@@ -1,14 +1,332 @@
#define RR_LOCALHOST_ONLY
using System;
using R3;
using RebootKit.Engine.Foundation;
using RebootKit.Engine.Main;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using RebootKit.Engine.Network;
using Steamworks;
using Steamworks.Data;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Logger = RebootKit.Engine.Foundation.Logger;
namespace RebootKit.Engine.Steam {
public class SteamNetworkManager : INetworkManager, ISocketManager, IConnectionManager {
static readonly Logger s_Logger = new Logger(nameof(SteamNetworkManager));
public const ulong k_ServerClientID = 0;
const int k_DefaultPort = 419;
class Client {
public ulong ClientID;
public Connection Connection;
}
readonly Dictionary<ulong, Client> m_Clients = new Dictionary<ulong, Client>();
SocketManager m_SocketManager;
ConnectionManager m_ConnectionManager;
float m_StatsRefreshTimer;
public INetworkManagerDelegate Delegate { get; set; }
public ulong LocalClientID {
get {
return SteamClient.SteamId;
}
}
public NetworkManagerStats Stats { get; } = new NetworkManagerStats();
// @NOTE: Set this before starting the client to specify which server to connect to.
public ulong TargetSteamID;
public SteamNetworkManager() {
SteamNetworkingUtils.InitRelayNetworkAccess();
SteamNetworkingUtils.OnDebugOutput += SteamDebugOutput;
SteamNetworkingUtils.DebugLevel = NetDebugOutput.None;
}
public void Dispose() {
SteamNetworkingUtils.OnDebugOutput -= SteamDebugOutput;
StopHost();
Disconnect();
}
void SteamDebugOutput(NetDebugOutput output, string msg) {
s_Logger.Info($"Output: {output} - {msg}");
}
//
// @MARK: Server
//
public bool IsServer() {
return m_SocketManager != null;
}
public bool StartHost() {
try {
TargetSteamID = SteamClient.SteamId;
m_SocketManager = SteamNetworkingSockets.CreateRelaySocket<SocketManager>(k_DefaultPort);
m_SocketManager.Interface = this;
m_ConnectionManager =
SteamNetworkingSockets.ConnectRelay<ConnectionManager>(TargetSteamID, k_DefaultPort);
m_ConnectionManager.Interface = this;
SteamFriends.SetRichPresence("connect", LocalClientID.ToString());
Stats.Reset();
Delegate?.OnServerStarted();
Delegate?.OnClientStarted();
} catch (Exception e) {
s_Logger.Error($"Failed to create server: {e.Message}");
m_SocketManager = null;
return false;
}
return true;
}
public void StopHost() {
if (!IsServer()) {
return;
}
s_Logger.Info("Stopping server...");
SteamFriends.SetRichPresence("connect", null);
foreach (Client client in m_Clients.Values) {
client.Connection.Close();
}
m_Clients.Clear();
m_SocketManager.Close();
m_SocketManager = null;
Delegate?.OnClientStopped();
Delegate?.OnServerStopped();
}
//
// @MARK: Client
//
public bool IsClient() {
return m_ConnectionManager != null;
}
public bool StartClient() {
if (IsClient()) {
s_Logger.Error("Cannot start client while already connected.");
return false;
}
s_Logger.Info("Connecting to server with steam ID: " + TargetSteamID);
try {
m_ConnectionManager =
SteamNetworkingSockets.ConnectRelay<ConnectionManager>(TargetSteamID, k_DefaultPort);
m_ConnectionManager.Interface = this;
Stats.Reset();
Delegate?.OnClientStarted();
} catch (Exception e) {
s_Logger.Error($"Failed to connect to server with ID {TargetSteamID}: {e.Message}");
m_ConnectionManager = null;
return false;
}
return true;
}
public void Disconnect() {
if (!IsClient()) {
return;
}
s_Logger.Info("Disconnecting from server...");
m_ConnectionManager.Close();
m_ConnectionManager = null;
Delegate?.OnClientStopped();
}
//
// @MARK: Data Sending/Receiving
//
public void Send(ulong clientID, NativeSlice<byte> data, SendMode mode) {
if (data.Length == 0) {
s_Logger.Error("Cannot send empty data.");
return;
}
unsafe {
Send(clientID, (byte*) data.GetUnsafePtr(), data.Length, mode);
}
}
public unsafe void Send(ulong clientID, byte* data, int length, SendMode mode) {
if (IsServer()) {
if (clientID == k_ServerClientID || clientID == LocalClientID) {
NativeArray<byte> dataArray = new NativeArray<byte>(length, Allocator.Temp);
UnsafeUtility.MemCpy(dataArray.GetUnsafePtr(), data, length);
MessageReceived(LocalClientID, dataArray);
return;
}
if (!m_Clients.TryGetValue(clientID, out Client client)) {
s_Logger.Error($"Client with ID {clientID} not found.");
return;
}
Result sendResult = client.Connection.SendMessage((IntPtr) data, length, GetSteamSendType(mode));
if (sendResult == Result.OK) {
if (mode == SendMode.Reliable) {
Stats.ReliableBytesSent += (ulong) length;
} else if (mode == SendMode.Unreliable) {
Stats.UnreliableBytesSent += (ulong) length;
}
} else {
s_Logger.Error($"Failed to send message to clientID, {clientID}. Result: {sendResult}.");
}
} else if (IsClient()) {
if (clientID != k_ServerClientID) {
s_Logger.Error($"Client can only send messages to the server (clientID must be {k_ServerClientID.ToString()}).");
return;
}
Result sendResult = m_ConnectionManager.Connection.SendMessage((IntPtr) data,
length,
GetSteamSendType(mode));
if (sendResult == Result.OK) {
if (mode == SendMode.Reliable) {
Stats.ReliableBytesSent += (ulong) length;
} else if (mode == SendMode.Unreliable) {
Stats.UnreliableBytesSent += (ulong) length;
}
} else {
s_Logger.Error($"Failed to send message to server. Result: {sendResult}. Flushing and retrying...");
}
} else {
s_Logger.Error("Cannot send data, server or client is not started.");
}
}
void MessageReceived(ulong senderID, NativeArray<byte> data) {
Delegate?.OnMessageReceived(senderID, data);
}
public void Tick() {
m_SocketManager?.Receive();
m_ConnectionManager?.Receive();
m_StatsRefreshTimer -= UnityEngine.Time.deltaTime;
if (m_StatsRefreshTimer <= 0f) {
m_StatsRefreshTimer = 1.0f;
Stats.ReliableBytesSentPerSecond = Stats.ReliableBytesSent;
Stats.UnreliableBytesSentPerSecond = Stats.UnreliableBytesSent;
Stats.BytesReceivedPerSecond = Stats.BytesReceived;
Stats.ReliableBytesSent = 0;
Stats.UnreliableBytesSent = 0;
Stats.BytesReceived = 0;
}
}
//
// @MARK: IConnectionManager
//
void ISocketManager.OnConnecting(Connection connection, ConnectionInfo info) {
s_Logger.Info($"OnConnecting: {connection.Id} - {info.Identity}");
connection.Accept();
}
void ISocketManager.OnConnected(Connection connection, ConnectionInfo info) {
if (!m_Clients.ContainsKey(info.Identity.SteamId)) {
s_Logger.Info($"OnConnected: {connection.Id} - {info.Identity}");
Client client = new Client {
ClientID = info.Identity.SteamId,
Connection = connection
};
m_Clients.Add(info.Identity.SteamId, client);
Delegate?.OnClientConnected(client.ClientID);
} else {
s_Logger.Error("Failed to add client, already exists: " + info.Identity.SteamId);
connection.Close();
}
}
void ISocketManager.OnDisconnected(Connection connection, ConnectionInfo info) {
s_Logger.Info($"OnDisconnected: {connection.Id} - {info.Identity}");
if (m_Clients.Remove(info.Identity.SteamId)) {
Delegate?.OnClientDisconnected(info.Identity.SteamId);
} else {
s_Logger.Error("Failed to remove client, not found: " + info.Identity.SteamId);
}
}
void ISocketManager.OnMessage(Connection connection,
NetIdentity identity,
IntPtr data,
int size,
long messageNum,
long recvTime,
int channel) {
NativeArray<byte> dataArray = new NativeArray<byte>(size, Allocator.Temp);
unsafe {
UnsafeUtility.MemCpy(dataArray.GetUnsafePtr(), (void*) data, size);
}
Stats.BytesReceived += (ulong) size;
MessageReceived(identity.SteamId, dataArray);
}
//
// @MARK: ISocketManager
//
void IConnectionManager.OnConnecting(ConnectionInfo info) { }
void IConnectionManager.OnConnected(ConnectionInfo info) {
Delegate?.OnClientConnected(info.Identity.SteamId);
}
void IConnectionManager.OnDisconnected(ConnectionInfo info) {
Delegate?.OnClientDisconnected(info.Identity.SteamId);
}
void IConnectionManager.OnMessage(IntPtr data, int size, long messageNum, long recvTime, int channel) {
NativeArray<byte> dataArray = new NativeArray<byte>(size, Allocator.Temp);
unsafe {
UnsafeUtility.MemCpy(dataArray.GetUnsafePtr(), (void*) data, size);
}
Stats.BytesReceived += (ulong) size;
MessageReceived(k_ServerClientID, dataArray);
}
//
// @MARK: Utilities
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static SendType GetSteamSendType(SendMode mode) {
return mode switch {
SendMode.Reliable => SendType.Reliable,
SendMode.Unreliable => SendType.Unreliable,
_ => throw new ArgumentOutOfRangeException(nameof(mode), mode, null)
};
}
}
// class SteamNetworkManager : INetworkManager {
// static readonly Logger s_Logger = new Logger(nameof(SteamNetworkManager));
//