-
Notifications
You must be signed in to change notification settings - Fork 1
/
Multiplay.cs
292 lines (237 loc) · 10.1 KB
/
Multiplay.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using PolkaDOTS.Multiplay.MultiplayStats;
using Unity.RenderStreaming;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
namespace PolkaDOTS.Multiplay
{
/// <summary>
/// Render stream connection manager, responsible for creating and destroying input and video streams on both
/// host and guest.
/// Adapted from RenderStreaming package Multiplay sample.
/// </summary>
public class Multiplay : SignalingHandlerBase,
IOfferHandler, IAddChannelHandler, IDisconnectHandler, IDeletedConnectionHandler, IConnectHandler
{
public SignalingManager renderStreaming;
public GameObject guestPrefab;
public GameObject playerPrefab;
public RawImage videoImage;
public StatsUI statsUI;
public GameObject defaultCamera;
private bool _initialized;
private bool guestConnected = false;
private SignalingHandlerBase currentHandler;
private GameObject currentPlayerObj;
private List<string> connectionIds = new();
private List<Component> streams = new();
public HashSet<string> disconnectedIds = new();
public Dictionary<string, GameObject> connectionPlayerObjects = new();
private MultiplaySettings settings;
private Vector3 initialPosition = new(0, 40, -4);
private void Awake()
{
defaultCamera.SetActive(false);
_initialized = false;
}
public void InitSettings()
{
if (_initialized)
{
return;
}
// Fetch the settings on awake
MultiplaySettingsManager.Instance.Initialize();
settings = MultiplaySettingsManager.Instance.Settings;
_initialized = true;
}
public override IEnumerable<Component> Streams => streams;
public bool IsGuestConnected()
{
return guestConnected;
}
// On delete or disconnect, simply mark this connection for destruction. Handle destruction in MultiplayPlayerSystem
public void OnDeletedConnection(SignalingEventData eventData)
{
Debug.Log($"Disconnecting {eventData.connectionId}");
disconnectedIds.Add(eventData.connectionId);
}
public void OnDisconnect(SignalingEventData eventData)
{
Debug.Log($"Disconnecting {eventData.connectionId}");
disconnectedIds.Add(eventData.connectionId);
}
public void DestroyMultiplayConnection(string connectionId)
{
//if (!connectionIds.Contains(connectionId))
// return;
//connectionIds.Remove(connectionId);
var playerObject = connectionPlayerObjects[connectionId];
var sender = playerObject.GetComponent<StreamSenderBase>();
var inputChannel = playerObject.GetComponent<InputReceiver>();
connectionPlayerObjects.Remove(connectionId);
Destroy(playerObject);
RemoveSender(connectionId, sender);
RemoveChannel(connectionId, inputChannel);
streams.Remove(sender);
streams.Remove(inputChannel);
if (ExistConnection(connectionId))
{
DeleteConnection(connectionId);
}
}
/// <summary>
/// This runs on RenderStreaming nodes, between thin clients and servers.
/// </summary>
/// <param name="data"></param>
public void OnOffer(SignalingEventData data)
{
Debug.Log($"Received streaming connection with id {data.connectionId}");
if (connectionIds.Contains(data.connectionId))
{
Debug.Log($"Already answered this connectionId : {data.connectionId}");
return;
}
connectionIds.Add(data.connectionId);
// Spawn object with camera and input component at a default location. This object will be synced
// with player transform on clients by PlayerInputSystem. These objects do not exist on the server.
var playerObj = Instantiate(playerPrefab, initialPosition, Quaternion.identity);
connectionPlayerObjects.Add(data.connectionId, playerObj);
var videoChannel = playerObj.GetComponent<StreamSenderBase>();
if (videoChannel is VideoStreamSender videoStreamSender && settings != null)
{
videoStreamSender.width = (uint)settings.StreamSize.x;
videoStreamSender.height = (uint)settings.StreamSize.y;
videoStreamSender.SetCodec(settings.SenderVideoCodec);
}
var inputChannel = playerObj.GetComponent<InputReceiver>();
streams.Add(videoChannel);
streams.Add(inputChannel);
//Debug.Log($"Pre-addsender");
AddSender(data.connectionId, videoChannel);
//Debug.Log($"Post-addesenderr");
AddChannel(data.connectionId, inputChannel);
SendAnswer(data.connectionId);
}
public void OnAddChannel(SignalingEventData data)
{
var obj = connectionPlayerObjects[data.connectionId];
var channels = obj.GetComponents<IDataChannel>();
var channel = channels.FirstOrDefault(_ => !_.IsLocal && !_.IsConnected);
channel?.SetChannel(data);
}
public void SetUpLocalPlayer()
{
Debug.Log("Creating local player object");
Cursor.lockState = CursorLockMode.Locked;
// We need to setup local input devices on local players
var hostPlayerObj = Instantiate(playerPrefab, initialPosition, Quaternion.identity);
var playerInput = hostPlayerObj.GetComponent<InputReceiver>();
playerInput.PerformPairingWithAllLocalDevices();
connectionPlayerObjects.Add("LOCALPLAYER", hostPlayerObj);
currentPlayerObj = hostPlayerObj;
}
public void SetUpHost(bool cloudOnly = false)
{
// Cloud only hosts do not run a local player
if (!cloudOnly)
{
SetUpLocalPlayer();
}
if (!settings.MultiplayEnabled)
{
Debug.Log("SetUpHost called but Multiplay disabled.");
return;
}
renderStreaming.useDefaultSettings = false;
Debug.Log($"Setting up multiplay host with signaling at {settings.SignalingAddress}");
renderStreaming.SetSignalingSettings(settings.SignalingSettings);
currentHandler = this;
statsUI.AddSignalingHandler(this);
renderStreaming.Run(handlers: new SignalingHandlerBase[] { this });
}
public void SetUpGuest(string url)
{
if (!settings.MultiplayEnabled)
{
Debug.Log("SetUpGuest called but Multiplay disabled.");
return;
}
Debug.Log("Removing any previous connection objects");
ClearConnectionPlayerObjects();
settings.SignalingAddress = url;
StartCoroutine(ConnectGuest());
}
public void OnConnect(SignalingEventData data)
{
//Debug.Log($"Disconnecting {eventData.connectionId}");
//disconnectedIds.Add(eventData.connectionId);
//data.connectionId
}
IEnumerator ConnectGuest()
{
var connectionId = $"{ApplicationConfig.UserID.Value}";//Guid.NewGuid().ToString("N");
var guestPlayer = Instantiate(guestPrefab);
var handler = guestPlayer.GetComponent<SingleConnection>();
statsUI.AddSignalingHandler(handler);
renderStreaming.useDefaultSettings = false;
renderStreaming.SetSignalingSettings(settings.SignalingSettings);
Debug.Log($"[{DateTime.Now.TimeOfDay}] Setting up multiplay guest with signaling at {settings.SignalingAddress}");
renderStreaming.Run(handlers: new SignalingHandlerBase[] { handler });
// Enable the video output
videoImage.gameObject.SetActive(true);
var receiveVideoViewer = guestPlayer.GetComponent<VideoStreamReceiver>();
receiveVideoViewer.OnUpdateReceiveTexture += texture => videoImage.texture = texture;
if (settings != null)
{
receiveVideoViewer.SetCodec(settings.ReceiverVideoCodec);
}
Cursor.lockState = CursorLockMode.Locked;
yield return new WaitUntil(() => handler.WSConnected());
handler.CreateConnection(connectionId);
yield return new WaitUntil(() => handler.IsConnected(connectionId));
guestConnected = true;
currentHandler = handler;
currentPlayerObj = guestPlayer;
}
void ClearConnectionPlayerObjects()
{
foreach (var (key, connectionPlayerObject) in connectionPlayerObjects)
{
Destroy(connectionPlayerObject);
}
connectionPlayerObjects.Clear();
}
public void StopMultiplay()
{
if (guestConnected)
{
currentHandler.DeleteConnection($"{ApplicationConfig.UserID.Value}");
}
else
{
// Stop any ongoing streams
foreach (var connID in connectionIds)
{
DestroyMultiplayConnection(connID);
}
connectionIds.Clear();
connectionPlayerObjects.Clear();
}
// Destroy instantiated gameobjects
if (currentPlayerObj != null)
{
Destroy(currentPlayerObj);
}
statsUI.RemoveSignalingHandler(currentHandler);
renderStreaming.RemoveSignalingHandler(currentHandler);
// restore default camera setup
videoImage.gameObject.SetActive(false);
//defaultCamera.SetActive(true);
}
}
}