BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / Platform / Samples / VrHoops / Scripts / P2PManager.cs

P2PManager.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
P2PManager.cs 16.6 KiB Download Raw
1namespace Oculus.Platform.Samples.VrHoops
2{
3 using UnityEngine;
4 using System.Collections.Generic;
5 using Oculus.Platform;
6 using Oculus.Platform.Models;
7 using System;
8 using UnityEngine.Assertions;
9
10 // This helper class coordinates establishing Peer-to-Peer connections between the
11 // players in the match. It tries to sychronize time between the devices and
12 // handles position update messages for the backboard and moving balls.
13 public class P2PManager
14 {
15 #region Member variables
16
17 // helper class to hold data we need for remote players
18 private class RemotePlayerData
19 {
20 // the last received Net connection state
21 public PeerConnectionState state;
22 // the Unity Monobehaviour
23 public RemotePlayer player;
24 // offset from my local time to the time of the remote host
25 public float remoteTimeOffset;
26 // the last ball update remote time, used to disgard out of order packets
27 public float lastReceivedBallsTime;
28 // remote Instance ID -> local MonoBahaviours for balls we're receiving updates on
29 public readonly Dictionary<int, P2PNetworkBall> activeBalls = new Dictionary<int, P2PNetworkBall>();
30 }
31
32 // authorized users to connect to and associated data
33 private readonly Dictionary<ulong, RemotePlayerData> m_remotePlayers = new Dictionary<ulong, RemotePlayerData>();
34
35 // when to send the next update to remotes on the state on my local balls
36 private float m_timeForNextBallUpdate;
37
38 private const byte TIME_SYNC_MESSAGE = 1;
39 private const uint TIME_SYNC_MESSAGE_SIZE = 1+4;
40 private const int TIME_SYNC_MESSAGE_COUNT = 7;
41 private const byte START_TIME_MESSAGE = 2;
42 private const uint START_TIME_MESSAGE_SIZE = 1+4;
43 private const byte BACKBOARD_UPDATE_MESSAGE = 3;
44 private const uint BACKBOARD_UPDATE_MESSAGE_SIZE = 1+4+12+12+12;
45 private const byte LOCAL_BALLS_UPDATE_MESSAGE = 4;
46 private const uint LOCAL_BALLS_UPDATE_MESSATE_SIZE_MAX = 1+4+(2*Player.MAX_BALLS*(1+4+12+12));
47 private const float LOCAL_BALLS_UPDATE_DELAY = 0.1f;
48 private const byte SCORE_UPDATE_MESSAGE = 5;
49 private const uint SCORE_UPDATE_MESSAGE_SIZE = 1 + 4;
50
51 // cache of local balls that we are sending updates for
52 private readonly Dictionary<int, P2PNetworkBall> m_localBalls = new Dictionary<int, P2PNetworkBall>();
53
54 // reusable buffer to read network data into
55 private readonly byte[] readBuffer = new byte[LOCAL_BALLS_UPDATE_MESSATE_SIZE_MAX];
56
57 // temporary time-sync cache of the calculated time offsets
58 private readonly Dictionary<ulong, List<float>> m_remoteSyncTimeCache = new Dictionary<ulong, List<float>>();
59
60 // temporary time-sync cache of the last sent message
61 private readonly Dictionary<ulong, float> m_remoteSentTimeCache = new Dictionary<ulong, float>();
62
63 // the delegate to handle start-time coordination
64 private StartTimeOffer m_startTimeOfferCallback;
65
66 #endregion
67
68 public P2PManager()
69 {
70 Net.SetPeerConnectRequestCallback(PeerConnectRequestCallback);
71 Net.SetConnectionStateChangedCallback(ConnectionStateChangedCallback);
72 }
73
74 public void UpdateNetwork()
75 {
76 if (m_remotePlayers.Count == 0)
77 return;
78
79 // check for new messages
80 Packet packet;
81 while ((packet = Net.ReadPacket()) != null)
82 {
83 if (!m_remotePlayers.ContainsKey(packet.SenderID))
84 continue;
85
86 packet.ReadBytes(readBuffer);
87
88 switch (readBuffer[0])
89 {
90 case TIME_SYNC_MESSAGE:
91 Assert.AreEqual(TIME_SYNC_MESSAGE_SIZE, packet.Size);
92 ReadTimeSyncMessage(packet.SenderID, readBuffer);
93 break;
94
95 case START_TIME_MESSAGE:
96 Assert.AreEqual(START_TIME_MESSAGE_SIZE, packet.Size);
97 ReceiveMatchStartTimeOffer(packet.SenderID, readBuffer);
98 break;
99
100 case BACKBOARD_UPDATE_MESSAGE:
101 Assert.AreEqual(BACKBOARD_UPDATE_MESSAGE_SIZE, packet.Size);
102 ReceiveBackboardUpdate(packet.SenderID, readBuffer);
103 break;
104
105 case LOCAL_BALLS_UPDATE_MESSAGE:
106 ReceiveBallTransforms(packet.SenderID, readBuffer, packet.Size);
107 break;
108
109 case SCORE_UPDATE_MESSAGE:
110 Assert.AreEqual(SCORE_UPDATE_MESSAGE_SIZE, packet.Size);
111 ReceiveScoredUpdate(packet.SenderID, readBuffer);
112 break;
113 }
114 }
115
116 if (Time.time >= m_timeForNextBallUpdate && m_localBalls.Count > 0)
117 {
118 SendLocalBallTransforms();
119 }
120 }
121
122 #region Connection Management
123
124 // adds a remote player to establish a connection to, or accept a connection from
125 public void AddRemotePlayer(RemotePlayer player)
126 {
127 if (!m_remotePlayers.ContainsKey (player.ID))
128 {
129 m_remotePlayers[player.ID] = new RemotePlayerData();
130 m_remotePlayers[player.ID].state = PeerConnectionState.Unknown;
131 m_remotePlayers [player.ID].player = player;
132
133 // ID comparison is used to decide who Connects and who Accepts
134 if (PlatformManager.MyID < player.ID)
135 {
136 Debug.Log ("P2P Try Connect to: " + player.ID);
137 Net.Connect (player.ID);
138 }
139 }
140 }
141
142 public void DisconnectAll()
143 {
144 foreach (var id in m_remotePlayers.Keys)
145 {
146 Net.Close(id);
147 }
148 m_remotePlayers.Clear();
149 }
150
151 void PeerConnectRequestCallback(Message<NetworkingPeer> msg)
152 {
153 if (m_remotePlayers.ContainsKey(msg.Data.ID))
154 {
155 Debug.LogFormat("P2P Accepting Connection request from {0}", msg.Data.ID);
156 Net.Accept(msg.Data.ID);
157 }
158 else
159 {
160 Debug.LogFormat("P2P Ignoring unauthorized Connection request from {0}", msg.Data.ID);
161 }
162 }
163
164 void ConnectionStateChangedCallback(Message<NetworkingPeer> msg)
165 {
166 Debug.LogFormat("P2P {0} Connection state changed to {1}", msg.Data.ID, msg.Data.State);
167
168 if (m_remotePlayers.ContainsKey(msg.Data.ID))
169 {
170 m_remotePlayers[msg.Data.ID].state = msg.Data.State;
171
172 switch (msg.Data.State)
173 {
174 case PeerConnectionState.Connected:
175 if (PlatformManager.MyID < msg.Data.ID)
176 {
177 SendTimeSyncMessage(msg.Data.ID);
178 }
179 break;
180
181 case PeerConnectionState.Timeout:
182 if (PlatformManager.MyID < msg.Data.ID)
183 {
184 Net.Connect(msg.Data.ID);
185 }
186 break;
187
188 case PeerConnectionState.Closed:
189 m_remotePlayers.Remove(msg.Data.ID);
190 break;
191 }
192 }
193 }
194
195 #endregion
196
197 #region Time Synchronizaiton
198
199 // This section implements some basic time synchronization between the players.
200 // The algorithm is:
201 // -Send a time-sync message and receive a time-sync message response
202 // -Estimate time offset
203 // -Repeat several times
204 // -Average values discarding any statistical anomalies
205 // Normally delays would be added in case there is intermittent network congestion
206 // however the match times are so short we don't do that here. Also, if one client
207 // pauses their game and Unity stops their simulation, all bets are off for time
208 // synchronization. Depending on the goals of your app, you could either reinitiate
209 // time synchronization, or just disconnect that player.
210
211 void SendTimeSyncMessage(ulong remoteID)
212 {
213 if (!m_remoteSyncTimeCache.ContainsKey(remoteID))
214 {
215 m_remoteSyncTimeCache[remoteID] = new List<float>();
216 }
217
218 float time = Time.realtimeSinceStartup;
219 m_remoteSentTimeCache[remoteID] = time;
220
221 byte[] buf = new byte[TIME_SYNC_MESSAGE_SIZE];
222 buf[0] = TIME_SYNC_MESSAGE;
223 int offset = 1;
224 PackFloat(time, buf, ref offset);
225
226 Net.SendPacket(remoteID, buf, SendPolicy.Reliable);
227 }
228
229 void ReadTimeSyncMessage(ulong remoteID, byte[] msg)
230 {
231 if (!m_remoteSentTimeCache.ContainsKey(remoteID))
232 {
233 SendTimeSyncMessage(remoteID);
234 return;
235 }
236
237 int offset = 1;
238 float remoteTime = UnpackFloat(msg, ref offset);
239 float now = Time.realtimeSinceStartup;
240 float latency = (now - m_remoteSentTimeCache[remoteID]) / 2;
241 float remoteTimeOffset = now - (remoteTime + latency);
242
243 m_remoteSyncTimeCache[remoteID].Add(remoteTimeOffset);
244
245 if (m_remoteSyncTimeCache[remoteID].Count < TIME_SYNC_MESSAGE_COUNT)
246 {
247 SendTimeSyncMessage(remoteID);
248 }
249 else
250 {
251 if (PlatformManager.MyID < remoteID)
252 {
253 // this client started the sync, need to send one last message to
254 // the remote so they can finish their sync calculation
255 SendTimeSyncMessage(remoteID);
256 }
257
258 // sort the times and remember the median
259 m_remoteSyncTimeCache[remoteID].Sort();
260 float median = m_remoteSyncTimeCache[remoteID][TIME_SYNC_MESSAGE_COUNT/2];
261
262 // calucate the mean and standard deviation
263 double mean = 0;
264 foreach (var time in m_remoteSyncTimeCache[remoteID])
265 {
266 mean += time;
267 }
268 mean /= TIME_SYNC_MESSAGE_COUNT;
269
270 double std_dev = 0;
271 foreach (var time in m_remoteSyncTimeCache[remoteID])
272 {
273 std_dev += (mean-time)*(mean-time);
274 }
275 std_dev = Math.Sqrt(std_dev)/TIME_SYNC_MESSAGE_COUNT;
276
277 // time delta is the mean of the values less than 1 standard deviation from the median
278 mean = 0;
279 int meanCount = 0;
280 foreach (var time in m_remoteSyncTimeCache[remoteID])
281 {
282 if (Math.Abs(time-median) < std_dev)
283 {
284 mean += time;
285 meanCount++;
286 }
287 }
288 mean /= meanCount;
289 Debug.LogFormat("Time offset to {0} is {1}", remoteID, mean);
290
291 m_remoteSyncTimeCache.Remove(remoteID);
292 m_remoteSentTimeCache.Remove(remoteID);
293 m_remotePlayers[remoteID].remoteTimeOffset = (float)mean;
294
295 // now that times are synchronized, lets try to coordinate the
296 // start time for the match
297 OfferMatchStartTime();
298 }
299 }
300
301 float ShiftRemoteTime(ulong remoteID, float remoteTime)
302 {
303 if (m_remotePlayers.ContainsKey(remoteID))
304 {
305 return remoteTime + m_remotePlayers[remoteID].remoteTimeOffset;
306 }
307 else
308 {
309 return remoteTime;
310 }
311 }
312
313 #endregion
314
315 #region Match Start Coordination
316
317 // Since all the clients will calculate a slightly different start time, this
318 // message tries to coordinate the match start time to be the lastest of all
319 // the clients in the match.
320
321 // Delegate to coordiate match start times - the return value is our start time
322 // and the argument is the remote start time, or 0 if that hasn't been given yet.
323 public delegate float StartTimeOffer(float remoteTime);
324
325 public StartTimeOffer StartTimeOfferCallback
326 {
327 private get { return m_startTimeOfferCallback; }
328 set { m_startTimeOfferCallback = value; }
329 }
330
331 void OfferMatchStartTime()
332 {
333 byte[] buf = new byte[START_TIME_MESSAGE_SIZE];
334 buf[0] = START_TIME_MESSAGE;
335 int offset = 1;
336 PackFloat(StartTimeOfferCallback(0), buf, ref offset);
337
338 foreach (var remoteID in m_remotePlayers.Keys)
339 {
340 if (m_remotePlayers [remoteID].state == PeerConnectionState.Connected)
341 {
342 Net.SendPacket (remoteID, buf, SendPolicy.Reliable);
343 }
344 }
345 }
346
347 void ReceiveMatchStartTimeOffer(ulong remoteID, byte[] msg)
348 {
349 int offset = 1;
350 float remoteTime = UnpackTime(remoteID, msg, ref offset);
351 StartTimeOfferCallback(remoteTime);
352 }
353
354 #endregion
355
356 #region Backboard Transforms
357
358 public void SendBackboardUpdate(float time, Vector3 pos, Vector3 moveDir, Vector3 nextMoveDir)
359 {
360 byte[] buf = new byte[BACKBOARD_UPDATE_MESSAGE_SIZE];
361 buf[0] = BACKBOARD_UPDATE_MESSAGE;
362 int offset = 1;
363 PackFloat(time, buf, ref offset);
364 PackVector3(pos, buf, ref offset);
365 PackVector3(moveDir, buf, ref offset);
366 PackVector3(nextMoveDir, buf, ref offset);
367
368 foreach (KeyValuePair<ulong,RemotePlayerData> player in m_remotePlayers)
369 {
370 if (player.Value.state == PeerConnectionState.Connected)
371 {
372 Net.SendPacket(player.Key, buf, SendPolicy.Reliable);
373 }
374 }
375 }
376
377 void ReceiveBackboardUpdate(ulong remoteID, byte[] msg)
378 {
379 int offset = 1;
380 float remoteTime = UnpackTime(remoteID, msg, ref offset);
381 Vector3 pos = UnpackVector3(msg, ref offset);
382 Vector3 moveDir = UnpackVector3(msg, ref offset);
383 Vector3 nextMoveDir = UnpackVector3(msg, ref offset);
384
385 var goal = m_remotePlayers [remoteID].player.Goal;
386 goal.RemoteBackboardUpdate(remoteTime, pos, moveDir, nextMoveDir);
387 }
388
389 #endregion
390
391 #region Ball Tansforms
392
393 public void AddNetworkBall(GameObject ball)
394 {
395 m_localBalls[ball.GetInstanceID()] = ball.AddComponent<P2PNetworkBall>();
396 }
397
398 public void RemoveNetworkBall(GameObject ball)
399 {
400 m_localBalls.Remove(ball.GetInstanceID());
401 }
402
403 void SendLocalBallTransforms()
404 {
405 m_timeForNextBallUpdate = Time.time + LOCAL_BALLS_UPDATE_DELAY;
406
407 int msgSize = 1 + 4 + (m_localBalls.Count * (1 + 4 + 12 + 12));
408 byte[] sendBuffer = new byte[msgSize];
409 sendBuffer[0] = LOCAL_BALLS_UPDATE_MESSAGE;
410 int offset = 1;
411 PackFloat(Time.realtimeSinceStartup, sendBuffer, ref offset);
412
413 foreach (var ball in m_localBalls.Values)
414 {
415 PackBool(ball.IsHeld(), sendBuffer, ref offset);
416 PackInt32(ball.gameObject.GetInstanceID(), sendBuffer, ref offset);
417 PackVector3(ball.transform.localPosition, sendBuffer, ref offset);
418 PackVector3(ball.velocity, sendBuffer, ref offset);
419 }
420
421 foreach (KeyValuePair<ulong, RemotePlayerData> player in m_remotePlayers)
422 {
423 if (player.Value.state == PeerConnectionState.Connected)
424 {
425 Net.SendPacket(player.Key, sendBuffer, SendPolicy.Unreliable);
426 }
427 }
428 }
429
430 void ReceiveBallTransforms(ulong remoteID, byte[] msg, ulong msgLength)
431 {
432 int offset = 1;
433 float remoteTime = UnpackTime(remoteID, msg, ref offset);
434
435 // because we're using unreliable networking the packets could come out of order
436 // and the best thing to do is just ignore old packets because the data isn't
437 // very useful anyway
438 if (remoteTime < m_remotePlayers[remoteID].lastReceivedBallsTime)
439 return;
440
441 m_remotePlayers[remoteID].lastReceivedBallsTime = remoteTime;
442
443 // loop over all ball updates in the message
444 while (offset != (int)msgLength)
445 {
446 bool isHeld = UnpackBool(msg, ref offset);
447 int instanceID = UnpackInt32(msg, ref offset);
448 Vector3 pos = UnpackVector3(msg, ref offset);
449 Vector3 vel = UnpackVector3(msg, ref offset);
450
451 if (!m_remotePlayers[remoteID].activeBalls.ContainsKey(instanceID))
452 {
453 var newball = m_remotePlayers[remoteID].player.CreateBall().AddComponent<P2PNetworkBall>();
454 newball.transform.SetParent(m_remotePlayers[remoteID].player.transform.parent);
455 m_remotePlayers[remoteID].activeBalls[instanceID] = newball;
456 }
457 var ball = m_remotePlayers[remoteID].activeBalls[instanceID];
458 if (ball)
459 {
460 ball.ProcessRemoteUpdate(remoteTime, isHeld, pos, vel);
461 }
462 }
463 }
464
465 #endregion
466
467 #region Score Updates
468
469 public void SendScoreUpdate(uint score)
470 {
471 byte[] buf = new byte[SCORE_UPDATE_MESSAGE_SIZE];
472 buf[0] = SCORE_UPDATE_MESSAGE;
473 int offset = 1;
474 PackUint32(score, buf, ref offset);
475
476 foreach (KeyValuePair<ulong, RemotePlayerData> player in m_remotePlayers)
477 {
478 if (player.Value.state == PeerConnectionState.Connected)
479 {
480 Net.SendPacket(player.Key, buf, SendPolicy.Reliable);
481 }
482 }
483 }
484
485 void ReceiveScoredUpdate(ulong remoteID, byte[] msg)
486 {
487 int offset = 1;
488 uint score = UnpackUint32(msg, ref offset);
489
490 m_remotePlayers[remoteID].player.ReceiveRemoteScore(score);
491 }
492 #endregion
493
494 #region Serialization
495
496 // This region contains basic data serialization logic. This sample doesn't warrant
497 // much optimization, but the opportunites are ripe those interested in the topic.
498
499 void PackVector3(Vector3 vec, byte[] buf, ref int offset)
500 {
501 PackFloat(vec.x, buf, ref offset);
502 PackFloat(vec.y, buf, ref offset);
503 PackFloat(vec.z, buf, ref offset);
504 }
505
506 Vector3 UnpackVector3(byte[] buf, ref int offset)
507 {
508 Vector3 vec;
509 vec.x = UnpackFloat(buf, ref offset);
510 vec.y = UnpackFloat(buf, ref offset);
511 vec.z = UnpackFloat(buf, ref offset);
512 return vec;
513 }
514
515 void PackQuaternion(Quaternion quat, byte[] buf, ref int offset)
516 {
517 PackFloat(quat.x, buf, ref offset);
518 PackFloat(quat.y, buf, ref offset);
519 PackFloat(quat.z, buf, ref offset);
520 PackFloat(quat.w, buf, ref offset);
521 }
522
523 void PackFloat(float value, byte[] buf, ref int offset)
524 {
525 Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4);
526 offset = offset + 4;
527 }
528
529 float UnpackFloat(byte[] buf, ref int offset)
530 {
531 float value = BitConverter.ToSingle(buf, offset);
532 offset += 4;
533 return value;
534 }
535
536 float UnpackTime(ulong remoteID, byte[] buf, ref int offset)
537 {
538 return ShiftRemoteTime(remoteID, UnpackFloat(buf, ref offset));
539 }
540
541 void PackInt32(int value, byte[] buf, ref int offset)
542 {
543 Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4);
544 offset = offset + 4;
545 }
546
547 int UnpackInt32(byte[] buf, ref int offset)
548 {
549 int value = BitConverter.ToInt32(buf, offset);
550 offset += 4;
551 return value;
552 }
553
554 void PackUint32(uint value, byte[] buf, ref int offset)
555 {
556 Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4);
557 offset = offset + 4;
558 }
559
560 uint UnpackUint32(byte[] buf, ref int offset)
561 {
562 uint value = BitConverter.ToUInt32(buf, offset);
563 offset += 4;
564 return value;
565 }
566
567 void PackBool(bool value, byte[] buf, ref int offset)
568 {
569 buf[offset++] = (byte)(value ? 1 : 0);
570 }
571
572 bool UnpackBool(byte[] buf, ref int offset)
573 {
574 return buf[offset++] != 0;;
575 }
576
577 #endregion
578 }
579}