-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMirrorpunchSteam.cs
341 lines (282 loc) · 10.9 KB
/
MirrorpunchSteam.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Steamworks;
using Steamworks.Data;
using Mirror;
using static Mirror.Punch.MirrorpunchCommon;
namespace Mirror.Punch
{
/// <summary>
/// Mirror Transport for Steam using Facepunch.Steamworks
/// </summary>
public class MirrorpunchSteam : Transport
{
#region Instance vars
///--------------------------------------------------------------------
/// MirrorpunchSteam instance vars
///--------------------------------------------------------------------
[SerializeField]
[Tooltip("MirrorpunchSteam will attempt to initialize, maintain, and shutdown the Steamworks API")]
private bool _maintainClient = false;
[SerializeField]
[Tooltip("Your game's unique AppId")]
private uint _appId = 0;
[SerializeField]
[Tooltip("Max number of connections if acting as a server")]
private uint _maxConnections = 5;
[SerializeField]
[Tooltip("Rate to poll for packets, in milliseconds")]
private double _tickRate = TICKRATE_32;
[SerializeField]
[Tooltip("Allow or disallow P2P connects to fall back on Steam server relay if direct connection or NAT traversal can't be established")]
private bool _allowRelay = true;
[SerializeField]
[Tooltip("Will cause Available() to return false, regardless of other flags")]
private bool _enableTransport = true;
[SerializeField]
[Tooltip("Will disable transport functionality and cause Available() to return false if SteamClient.IsLoggedOn is false")]
private bool _forceOnline = false;
private MirrorpunchServer _server = null;
private MirrorpunchClient _client = null;
private bool _eventsRegistered = false;
private Action<int> _svConnected = null;
private Action<int> _svDisconnected = null;
private Action<int, byte[]> _svDataReceived = null;
private Action<int, Exception> _svError = null;
private Action _clConnected = null;
private Action _clDisconnected = null;
private Action<byte[]> _clDataReceived = null;
private Action<Exception> _clError = null;
#endregion Instance vars
#region Properties
///--------------------------------------------------------------------
/// MirrorpunchSteam properties
///--------------------------------------------------------------------
/// <summary>
/// MirrorpunchSteam will attempt to initialize, maintain, and shutdown the Steamworks API
/// </summary>
public bool MaintainClient => _maintainClient;
/// <summary>
/// Your game's unique AppId
/// </summary>
public uint AppId => _appId;
/// <summary>
/// Max number of connections if acting as a server
/// </summary>
public uint MaxConnections => _maxConnections;
/// <summary>
/// Rate to poll for packets, in milliseconds
/// </summary>
public double TickRate => _tickRate;
/// <summary>
/// Allow or disallow P2P connects to fall back on Steam server relay if direct connection or NAT traversal can't be established
/// </summary>
public bool AllowRelay => _allowRelay;
/// <summary>
/// Will disable transport functionality and cause Available() to return false, regardless of other flags
/// </summary>
public bool EnableTransport => _enableTransport;
/// <summary>
/// Will cause Available() to return false if SteamClient.IsLoggedOn is false
/// </summary>
public bool ForceOnline => _forceOnline;
public MirrorpunchServer Server => _server;
public MirrorpunchClient Client => _client;
#endregion Properties
#region Methods
///--------------------------------------------------------------------
/// MirrorpunchSteam methods
///--------------------------------------------------------------------
private void OnEnable()
{
if (MaintainClient)
{
try
{
if (AppId <= 0)
throw new Exception("Mirrorpunch: AppId is invalid");
SteamClient.Init(AppId);
}
catch (Exception e)
{
string error = $"Mirrorpunch: Exception when initializing SteamClient ({e.Message}), disabling transport";
_enableTransport = false;
Output.LogError(error);
}
}
if (EnableTransport)
{
InitCommon();
InitServerClient();
// Register events after server/client objects are initialized
RegisterMirrorEvents();
}
}
private void Start()
{
if (!SteamClient.IsValid)
{
_enableTransport = false;
Output.LogError("Mirrorpunch: SteamClient is invalid in Start, disabling transport");
return;
}
}
/// <summary>
/// Initialize common values
/// </summary>
private void InitCommon()
{
SteamNetworking.AllowP2PPacketRelay(_allowRelay);
MirrorpunchCommon.SetTickRate(_tickRate);
}
/// <summary>
/// Initialize the server and client objects
/// </summary>
private void InitServerClient()
{
_server = new MirrorpunchServer(this, _maxConnections);
_client = new MirrorpunchClient(this);
_server.Init();
_client.Init();
}
private void RegisterMirrorEvents()
{
// Server
_svConnected = (id) => OnServerConnected?.Invoke(id);
_svDisconnected = (id) => OnServerDisconnected?.Invoke(id);
_svDataReceived = (id, data) => OnServerDataReceived?.Invoke(id, new ArraySegment<byte>(data));
_svError = (id, exception) => OnServerError?.Invoke(id, exception);
Server.OnConnected += _svConnected;
Server.OnDisconnected += _svDisconnected;
Server.OnDataReceived += _svDataReceived;
Server.OnError += _svError;
// Client
_clConnected = () => OnClientConnected?.Invoke();
_clDisconnected = () => OnClientDisconnected?.Invoke();
_clDataReceived = (data) => OnClientDataReceived?.Invoke(new ArraySegment<byte>(data));
_clError = (exception) => OnClientError?.Invoke(exception);
Client.OnConnected += _clConnected;
Client.OnDisconnected += _clDisconnected;
Client.OnDataReceived += _clDataReceived;
Client.OnError += _clError;
_eventsRegistered = true;
}
private void UnregisterMirrorEvents()
{
// Server
Server.OnConnected -= _svConnected;
Server.OnDisconnected -= _svDisconnected;
Server.OnDataReceived -= _svDataReceived;
Server.OnError -= _svError;
_svConnected = null;
_svDisconnected = null;
_svDataReceived = null;
_svError = null;
// Client
Client.OnConnected -= _clConnected;
Client.OnDisconnected -= _clDisconnected;
Client.OnDataReceived -= _clDataReceived;
Client.OnError -= _clError;
_clConnected = null;
_clDisconnected = null;
_clDataReceived = null;
_clError = null;
_eventsRegistered = false;
}
/// <summary>
/// Set transport enabled/disabled
/// </summary>
public void SetEnableTransport(bool enabled)
{
_enableTransport = enabled;
}
/// <summary>
/// Returns false if the enable transport instance var is false, if SteamClient conditions are not met, and if the platform is WebGL
/// </summary>
public override bool Available()
{
// Check if the transport is disabled
if (!_enableTransport)
return false;
// Must be logged in to Steam Client
if (!SteamClient.IsValid)
return false;
// If force online is true, then SteamClient.IsLoggedOn must also be true
if (_forceOnline && !SteamClient.IsLoggedOn)
return false;
return Application.platform != RuntimePlatform.WebGLPlayer;
}
public override void ClientConnect(string id)
{
if(!ulong.TryParse(id, out ulong hostId))
{
Output.LogError($"Mirrorpunch: Could not parse string ({id}) into ulong, can't connect");
return;
}
Client.ConnectToId(hostId);
}
public override bool ClientConnected()
{
return Client.ClientConnected();
}
public override void ClientDisconnect()
{
Client.ClientDisconnect();
}
public override bool ClientSend(int channelId, byte[] data)
{
return Client.ClientSend(channelId, data);
}
public override int GetMaxPacketSize(int channelId = 0)
{
return MirrorpunchCommon.MP_PACKET_MAX;
}
/// <summary>
/// Checks if server is active
/// </summary>
public override bool ServerActive()
{
return Server.Active;
}
public override bool ServerDisconnect(int connectionId)
{
return Server.ServerDisconnect(connectionId);
}
public override string ServerGetClientAddress(int connectionId)
{
return Server.ServerGetClientAddress(connectionId);
}
public override bool ServerSend(int connectionId, int channelId, byte[] data)
{
return Server.ServerSend(connectionId, channelId, data);
}
public override void ServerStart()
{
Server.ServerStart();
}
public override void ServerStop()
{
Server.ServerStop();
}
public void LateUpdate ()
{
if(EnableTransport)
{
ProcessMessages(Client);
ProcessMessages(Server);
}
}
public override void Shutdown()
{
if (_maintainClient)
SteamClient.Shutdown();
if (_eventsRegistered)
UnregisterMirrorEvents();
_client?.CleanUp();
_server?.CleanUp();
}
#endregion Methods
}
}