Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

579 lines
17 KiB

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