-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathEOSHighFrequencyP2P.cs
More file actions
427 lines (365 loc) · 15.3 KB
/
Copy pathEOSHighFrequencyP2P.cs
File metadata and controls
427 lines (365 loc) · 15.3 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*
* Copyright (c) 2026 Epic Games Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace PlayEveryWare.EpicOnlineServices.Samples
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using UnityEngine;
using Epic.OnlineServices;
using Epic.OnlineServices.P2P;
using Utility;
public class EOSHighFrequencyPeer2PeerManager : IEOSSubManager
{
private P2PInterface P2PHandle;
private ulong ConnectionNotificationId;
private Dictionary<ProductUserId, ChatWithFriendData> ChatDataCache;
private bool ChatDataCacheDirty;
public UIPeer2PeerParticleController ParticleController;
public Transform parent;
public UIHighFrequencyPeer2PeerMenu owner;
public float packetSizeMB = 0.5f;
public int refreshRate = 60;
private float timer;
public bool sendActive = false;
private List<float> dataDump;
private const string CoordinateMessagePrefix = "m";
#if UNITY_EDITOR
void OnPlayModeChanged(UnityEditor.PlayModeStateChange modeChange)
{
if (modeChange == UnityEditor.PlayModeStateChange.ExitingPlayMode)
{
//prevent attempts to call native EOS code while exiting play mode, which crashes the editor
P2PHandle = null;
}
}
#endif
public EOSHighFrequencyPeer2PeerManager()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeChanged;
UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeChanged;
#endif
P2PHandle = EOSManager.Instance.GetEOSPlatformInterface().GetP2PInterface();
ChatDataCache = new Dictionary<ProductUserId, ChatWithFriendData>();
ChatDataCacheDirty = true;
updatePacketSize();
}
#if UNITY_EDITOR
~EOSHighFrequencyPeer2PeerManager()
{
UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeChanged;
}
#endif
public void updatePacketSize()
{
dataDump = new List<float>();
for (int i = 0; i < packetSizeMB * 256; i++)
{
dataDump.Add(i);
}
}
public void P2PUpdate()
{
timer += Time.deltaTime;
if (timer > 1 / refreshRate)
{
timer = 0;
SendMessageHF();
}
}
void SendMessageHF()
{
SendMessage(owner.GetCurrentFriendId(), dataDump.ToString());
}
public bool GetChatDataCache(out Dictionary<ProductUserId, ChatWithFriendData> ChatDataCache)
{
ChatDataCache = this.ChatDataCache;
return ChatDataCacheDirty;
}
private void RefreshNATType()
{
var options = new QueryNATTypeOptions();
P2PHandle.QueryNATType(ref options, null, OnRefreshNATTypeFinished);
}
public NATType GetNATType()
{
var options = new GetNATTypeOptions();
Result result = P2PHandle.GetNATType(ref options, out NATType natType);
if (result == Result.NotFound)
{
return NATType.Unknown;
}
if (result != Result.Success)
{
Debug.LogErrorFormat("EOS P2PNAT GetNatType: error while retrieving NAT Type: {0}", result);
return NATType.Unknown;
}
return natType;
}
public void OnLoggedIn()
{
RefreshNATType();
SubscribeToConnectionRequest();
}
public void OnLoggedOut()
{
UnsubscribeFromConnectionRequests();
}
private void OnRefreshNATTypeFinished(ref OnQueryNATTypeCompleteInfo data)
{
//if (data == null)
//{
// Debug.LogError("P2P (OnRefreshNATTypeFinished): data is null");
// return;
//}
if (data.ResultCode != Result.Success)
{
Debug.LogErrorFormat("P2p (OnRefreshNATTypeFinished): RefreshNATType error: {0}", data.ResultCode);
return;
}
Debug.Log("P2p (OnRefreshNATTypeFinished): RefreshNATType Completed");
}
public void SendMessage(ProductUserId friendId, string message)
{
if (friendId == null || !friendId.IsValid())
{
Debug.LogError("EOS P2PNAT SendMessage: bad input data: account id is wrong.");
return;
}
if (string.IsNullOrEmpty(message))
{
Debug.LogError("EOS P2PNAT SendMessage: bad input data message is empty.");
return;
}
// Update Cache
ChatEntry chatEntry = new ChatEntry()
{
isOwnEntry = true,
Message = message
};
if (ChatDataCache.TryGetValue(friendId, out ChatWithFriendData chatData))
{
chatData.ChatLines.Enqueue(chatEntry);
ChatDataCacheDirty = true;
}
else
{
ChatWithFriendData newChatData = new ChatWithFriendData(friendId);
newChatData.ChatLines.Enqueue(chatEntry);
ChatDataCache.Add(friendId, newChatData);
ChatDataCacheDirty = true;
}
// Send Message
SocketId socketId = new SocketId()
{
SocketName = "CHAT"
};
SendPacketOptions options = new SendPacketOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RemoteUserId = friendId,
SocketId = socketId,
AllowDelayedDelivery = true,
Channel = 0,
Reliability = PacketReliability.ReliableOrdered,
Data = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message))
};
Result result = P2PHandle.SendPacket(ref options);
if (result != Result.Success)
{
Debug.LogErrorFormat("EOS P2PNAT SendMessage: error while sending data, code: {0}", result);
return;
}
Debug.Log("EOS P2PNAT SendMessage: Message successfully sent to user.");
/*else if (message.type == messageType.coordinatesMessage)
{
string rawData = ("m" + message.xPos.ToString() + "," + message.yPos.ToString());
// Send Message
SocketId socketId = new SocketId()
{
SocketName = "CHAT"
};
SendPacketOptions options = new SendPacketOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RemoteUserId = friendId,
SocketId = socketId,
AllowDelayedDelivery = true,
Channel = 0,
Reliability = PacketReliability.ReliableOrdered,
Data = new ArraySegment<byte>(Encoding.UTF8.GetBytes(rawData))
};
Result result = P2PHandle.SendPacket(ref options);
if (result != Result.Success)
{
Debug.LogErrorFormat("EOS P2PNAT SendMessage: error while sending data, code: {0}", result);
return;
}
}
else
{
Debug.Log("EOS P2PNAT SendMessage: Message content was not valid.");
}*/
}
public ProductUserId HandleReceivedMessages()
{
if (P2PHandle == null)
{
return null;
}
ReceivePacketOptions options = new ReceivePacketOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
MaxDataSizeBytes = 4096,
RequestedChannel = null
};
var getNextReceivedPacketSizeOptions = new GetNextReceivedPacketSizeOptions
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RequestedChannel = null
};
P2PHandle.GetNextReceivedPacketSize(ref getNextReceivedPacketSizeOptions, out uint nextPacketSizeBytes);
byte[] data = new byte[nextPacketSizeBytes];
var dataSegment = new ArraySegment<byte>(data);
ProductUserId peerId = null;
SocketId socketId = default;
Result result = P2PHandle.ReceivePacket(ref options, ref peerId, ref socketId, out byte outChannel, dataSegment, out uint bytesWritten);
if (result == Result.NotFound)
{
// no packets
return null;
}
else if (result == Result.Success)
{
//Log the message
Debug.LogFormat("Message received: peerId={0}, socketId={1}, data={2}", peerId.Redact(), socketId, Encoding.UTF8.GetString(data));
if (!peerId.IsValid())
{
Debug.LogError($"{nameof(EOSHighFrequencyPeer2PeerManager)} {nameof(HandleReceivedMessages)}: ProductUserId for '{peerId.Redact()}' is not valid!");
return null;
}
string message = System.Text.Encoding.UTF8.GetString(data);
if (string.IsNullOrEmpty(message))
{
Debug.LogWarning($"{nameof(EOSHighFrequencyPeer2PeerManager)} {nameof(HandleReceivedMessages)}: Received an empty message.");
return null;
}
else if (TryDeserializeCoordinatePacket(message, out float xPos, out float yPos))
{
Debug.Log($"{nameof(EOSHighFrequencyPeer2PeerManager)} {nameof(HandleReceivedMessages)}: Particle coordinates received: x={xPos}, y={yPos}");
if (owner != null && owner.ParticleManager != null)
{
owner.ParticleManager.SpawnParticles(xPos, yPos);
}
else
{
Debug.LogWarning($"{nameof(EOSHighFrequencyPeer2PeerManager)} {nameof(HandleReceivedMessages)}: ParticleManager or owner reference is missing.");
}
return peerId;
}
else if (message.StartsWith(CoordinateMessagePrefix, StringComparison.Ordinal))
{
Debug.LogWarning($"{nameof(EOSHighFrequencyPeer2PeerManager)} {nameof(HandleReceivedMessages)}: Malformed coordinate message received.");
}
}
return null;
}
private void SubscribeToConnectionRequest()
{
if (ConnectionNotificationId == 0)
{
SocketId socketId = new SocketId()
{
SocketName = "CHAT"
};
AddNotifyPeerConnectionRequestOptions options = new AddNotifyPeerConnectionRequestOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
SocketId = socketId
};
ConnectionNotificationId = P2PHandle.AddNotifyPeerConnectionRequest(ref options, null, OnIncomingConnectionRequest);
if (ConnectionNotificationId == 0)
{
Debug.Log("EOS P2PNAT SubscribeToConnectionRequests: could not subscribe, bad notification id returned.");
}
}
}
private void UnsubscribeFromConnectionRequests()
{
if (ConnectionNotificationId != 0)//check to prevent warnings when done unnecessarily during p2p startup
{
P2PHandle.RemoveNotifyPeerConnectionRequest(ConnectionNotificationId);
ConnectionNotificationId = 0;
}
}
private void OnIncomingConnectionRequest(ref OnIncomingConnectionRequestInfo data)
{
//if (data == null)
//{
// Debug.LogError("P2P (OnIncomingConnectionRequest): data is null");
// return;
//}
if (!(bool)data.SocketId?.SocketName.Equals("CHAT"))
{
Debug.LogError("P2p (OnIncomingConnectionRequest): bad socket id");
return;
}
SocketId socketId = new SocketId()
{
SocketName = "CHAT"
};
AcceptConnectionOptions options = new AcceptConnectionOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RemoteUserId = data.RemoteUserId,
SocketId = socketId
};
Result result = P2PHandle.AcceptConnection(ref options);
if (result != Result.Success)
{
Debug.LogErrorFormat("P2p (OnIncomingConnectionRequest): error while accepting connection, code: {0}", result);
}
}
public static string SerializeCoordinatePacket(float x, float y)
{
// Coordinate packets are serialized as: "m<x>,<y>".
// The leading "m" identifies a coordinate message.
return string.Format(CultureInfo.InvariantCulture, "{0}{1},{2}", CoordinateMessagePrefix, x, y);
}
public static bool TryDeserializeCoordinatePacket(string packet, out float x, out float y)
{
x = 0f;
y = 0f;
if (string.IsNullOrEmpty(packet) || !packet.StartsWith(CoordinateMessagePrefix, StringComparison.Ordinal))
{
return false;
}
// Remove the CoordinateMessagePrefix via Substring(1) before splitting "<x>,<y>".
string[] parts = packet.Substring(1).Split(',');
return parts.Length == 2
&& float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out x)
&& float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out y);
}
}
}