NetworkGamer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. using Microsoft.Xna.Framework.GamerServices;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Net;
  6. namespace Microsoft.Xna.Framework.Net
  7. {
  8. /// <summary>
  9. /// Represents a player in a network session.
  10. /// </summary>
  11. public class NetworkGamer : INetworkGamer
  12. {
  13. private static NetworkGamer localGamer;
  14. private readonly NetworkSession session;
  15. private readonly string id;
  16. private readonly bool isLocal;
  17. private readonly bool isHost;
  18. private string gamertag;
  19. private bool isReady;
  20. private object tag;
  21. // Network performance properties
  22. private TimeSpan roundtripTime = TimeSpan.Zero;
  23. /// <summary>
  24. /// Gets the unique identifier for this gamer.
  25. /// </summary>
  26. public string Id => id;
  27. /// <summary>
  28. /// Gets whether this gamer is the local player.
  29. /// </summary>
  30. public bool IsLocal => isLocal;
  31. /// <summary>
  32. /// Gets whether this gamer is the host of the session.
  33. /// </summary>
  34. public bool IsHost => isHost;
  35. /// <summary>
  36. /// Gets or sets the gamertag for this gamer.
  37. /// </summary>
  38. public string Gamertag
  39. {
  40. get => gamertag;
  41. set => gamertag = value ?? throw new ArgumentNullException(nameof(value));
  42. }
  43. /// <summary>
  44. /// Gets or sets whether this gamer is ready to start the game.
  45. /// </summary>
  46. public bool IsReady
  47. {
  48. get => isReady;
  49. set
  50. {
  51. if (isReady != value)
  52. {
  53. isReady = value;
  54. // Notify session of readiness change if this is the local gamer
  55. if (isLocal)
  56. {
  57. session?.NotifyReadinessChanged(this);
  58. }
  59. }
  60. }
  61. }
  62. /// <summary>
  63. /// Gets or sets custom data associated with this gamer.
  64. /// </summary>
  65. public object Tag
  66. {
  67. get => tag;
  68. set => tag = value;
  69. }
  70. /// <summary>
  71. /// Gets the machine for this network gamer.
  72. /// </summary>
  73. public NetworkMachine Machine => null; // Mock implementation
  74. /// <summary>
  75. /// Gets whether data is available to be received from this gamer.
  76. /// </summary>
  77. public bool IsDataAvailable => incomingPackets.Count > 0;
  78. /// <summary>
  79. /// Gets the SignedInGamer associated with this NetworkGamer.
  80. /// </summary>
  81. public SignedInGamer SignedInGamer => SignedInGamer.Current;
  82. /// <summary>
  83. /// Gets whether this gamer is muted by the local user.
  84. /// </summary>
  85. public bool IsMutedByLocalUser => false; // Mock implementation
  86. /// <summary>
  87. /// Gets whether this gamer is currently talking.
  88. /// </summary>
  89. public bool IsTalking => false; // Mock implementation
  90. /// <summary>
  91. /// Gets whether this gamer has voice capabilities.
  92. /// </summary>
  93. public bool HasVoice => false; // Mock implementation
  94. // Add to NetworkGamer class
  95. private readonly Queue<(byte[] Data, NetworkGamer Sender)> incomingPackets = new Queue<(byte[], NetworkGamer)>();
  96. internal NetworkGamer(NetworkSession session, string id, bool isLocal, bool isHost, string gamertag)
  97. {
  98. this.session = session;
  99. this.id = id;
  100. this.isLocal = isLocal;
  101. this.isHost = isHost;
  102. this.gamertag = gamertag;
  103. }
  104. /// <summary>
  105. /// Receives data from this gamer.
  106. /// </summary>
  107. /// <param name="data">Array to receive the data into.</param>
  108. /// <param name="sender">The gamer who sent the data.</param>
  109. /// <returns>The number of bytes received.</returns>
  110. public int ReceiveData(byte[] data, out NetworkGamer sender)
  111. {
  112. if (data == null)
  113. throw new ArgumentNullException(nameof(data));
  114. sender = null;
  115. // Check if data is available
  116. if (!IsDataAvailable)
  117. return 0;
  118. var packet = incomingPackets.Dequeue();
  119. sender = packet.Sender;
  120. int length = Math.Min(data.Length, packet.Data.Length);
  121. Array.Copy(packet.Data, data, length);
  122. return length;
  123. }
  124. public int ReceiveData(byte[] data, int offset, out NetworkGamer sender)
  125. {
  126. if (data == null)
  127. throw new ArgumentNullException(nameof(data));
  128. if (offset < 0 || offset >= data.Length)
  129. throw new ArgumentOutOfRangeException(nameof(offset), "Offset must be within the bounds of the data array.");
  130. sender = null;
  131. // Check if data is available
  132. if (!IsDataAvailable)
  133. return 0;
  134. var packet = incomingPackets.Dequeue();
  135. sender = packet.Sender;
  136. int length = Math.Min(data.Length - offset, packet.Data.Length);
  137. Array.Copy(packet.Data, 0, data, offset, length);
  138. return length;
  139. }
  140. /// <summary>
  141. /// Receives data from this gamer using PacketReader.
  142. /// </summary>
  143. /// <param name="data">Array to receive the data into.</param>
  144. /// <param name="sender">The gamer who sent the data.</param>
  145. /// <returns>The number of bytes received.</returns>
  146. public int ReceiveData(PacketReader reader, out NetworkGamer sender)
  147. {
  148. // Ensure the session is valid
  149. if (session == null)
  150. throw new InvalidOperationException("Network session is not initialized.");
  151. if (reader == null)
  152. throw new ArgumentNullException(nameof(reader));
  153. sender = null;
  154. // Check if data is available
  155. if (!IsDataAvailable)
  156. return 0;
  157. var packet = incomingPackets.Dequeue();
  158. sender = packet.Sender;
  159. reader.Reset(packet.Data);
  160. return packet.Data.Length;
  161. }
  162. /// <summary>
  163. /// Sends data to other gamers in the session.
  164. /// </summary>
  165. /// <param name="data">The data to send.</param>
  166. /// <param name="options">Send options.</param>
  167. public void SendData(byte[] data, SendDataOptions options)
  168. {
  169. if (data == null)
  170. throw new ArgumentNullException(nameof(data));
  171. if (!Enum.IsDefined(typeof(SendDataOptions), options))
  172. throw new ArgumentOutOfRangeException(nameof(options), "Invalid send data option.");
  173. SendDataInternal(data, options, session.AllGamers);
  174. }
  175. /// <summary>
  176. /// Sends data to specific gamers in the session.
  177. /// </summary>
  178. /// <param name="data">The data to send.</param>
  179. /// <param name="options">Send options.</param>
  180. /// <param name="recipients">The gamers to send to.</param>
  181. public void SendData(byte[] data, SendDataOptions options, IEnumerable<NetworkGamer> recipients)
  182. {
  183. if (data == null)
  184. throw new ArgumentNullException(nameof(data));
  185. if (!Enum.IsDefined(typeof(SendDataOptions), options))
  186. throw new ArgumentOutOfRangeException(nameof(options), "Invalid send data option.");
  187. SendDataInternal(data, options, recipients);
  188. }
  189. /// <summary>
  190. /// Sends data using PacketWriter to specific recipients.
  191. /// </summary>
  192. /// <param name="data">The data to send.</param>
  193. /// <param name="options">Send options.</param>
  194. /// <param name="recipients">The gamers to send to.</param>
  195. public void SendData(PacketWriter data, SendDataOptions options, IEnumerable<NetworkGamer> recipients)
  196. {
  197. if (data == null)
  198. throw new ArgumentNullException(nameof(data), "PacketWriter cannot be null.");
  199. if (!Enum.IsDefined(typeof(SendDataOptions), options))
  200. throw new ArgumentOutOfRangeException(nameof(options), "Invalid send data option.");
  201. if (recipients == null)
  202. throw new ArgumentNullException(nameof(recipients));
  203. byte[] serializedData = data.GetData();
  204. SendDataInternal(serializedData, options, recipients);
  205. data.Position = 0; // Reset position after sending
  206. }
  207. /// <summary>
  208. /// Sends data using PacketWriter.
  209. /// </summary>
  210. /// <param name="data">The data to send.</param>
  211. /// <param name="options">Send options.</param>
  212. public void SendData(PacketWriter data, SendDataOptions options)
  213. {
  214. SendData(data, options, session.AllGamers);
  215. }
  216. /// <summary>
  217. /// Sends data using PacketWriter to a specific recipient.
  218. /// </summary>
  219. /// <param name="data">The data to send.</param>
  220. /// <param name="options">Send options.</param>
  221. /// <param name="recipient">The gamer to send to.</param>
  222. public void SendData(PacketWriter data, SendDataOptions options, NetworkGamer recipient)
  223. {
  224. SendData(data, options, new[] { recipient });
  225. }
  226. /// <summary>
  227. /// Sends byte array data to a specific recipient.
  228. /// </summary>
  229. /// <param name="data">The data to send.</param>
  230. /// <param name="options">Send options.</param>
  231. /// <param name="recipient">The gamer to send to.</param>
  232. public void SendData(byte[] data, SendDataOptions options, NetworkGamer recipient)
  233. {
  234. SendData(data, options, new[] { recipient });
  235. }
  236. /// <summary>
  237. /// Gets the current round-trip time for network communication with this gamer.
  238. /// </summary>
  239. public TimeSpan RoundtripTime => roundtripTime;
  240. /// <summary>
  241. /// Updates the round-trip time (internal use).
  242. /// </summary>
  243. internal void UpdateRoundtripTime(TimeSpan newRoundtripTime)
  244. {
  245. roundtripTime = newRoundtripTime;
  246. }
  247. public override string ToString()
  248. {
  249. return $"{Gamertag} ({(IsLocal ? "Local" : "Remote")}, {(IsHost ? "Host" : "Player")})";
  250. }
  251. public override bool Equals(object obj)
  252. {
  253. return obj is NetworkGamer other && Id == other.Id;
  254. }
  255. public override int GetHashCode()
  256. {
  257. return Id.GetHashCode();
  258. }
  259. /// <summary>
  260. /// Gets the local gamer.
  261. /// </summary>
  262. public static NetworkGamer LocalGamer
  263. {
  264. get => localGamer;
  265. internal set => localGamer = value;
  266. }
  267. /// <summary>
  268. /// Implicit conversion from NetworkGamer to SignedInGamer.
  269. /// </summary>
  270. public static implicit operator SignedInGamer(NetworkGamer gamer)
  271. {
  272. return gamer?.SignedInGamer;
  273. }
  274. private void SendDataInternal(byte[] data, SendDataOptions options, IEnumerable<NetworkGamer> recipients)
  275. {
  276. switch (session.SessionType)
  277. {
  278. case NetworkSessionType.SystemLink:
  279. // Ensure the sender (host) also processes its own outbound packet so
  280. // gameplay code (e.g. WorldSetup) follows the same receive path.
  281. bool includeSelf = false;
  282. foreach (var recipient in recipients)
  283. {
  284. if (recipient == this)
  285. {
  286. includeSelf = true;
  287. continue;
  288. }
  289. session.SendDataToGamer(recipient, data, options);
  290. }
  291. // Loopback to self if included in recipients (typical when using session.AllGamers).
  292. if (includeSelf && IsLocal)
  293. {
  294. // Clone to avoid later mutation issues.
  295. var clone = new byte[data.Length];
  296. Buffer.BlockCopy(data, 0, clone, 0, data.Length);
  297. EnqueueIncomingPacket(clone, this);
  298. }
  299. break;
  300. case NetworkSessionType.Local:
  301. // Direct in-process delivery to every local gamer (split-screen scenario).
  302. // Reliable/in-order semantics are trivially satisfied.
  303. var delivered = new HashSet<NetworkGamer>();
  304. foreach (var recipient in recipients)
  305. {
  306. if (recipient == null || !recipient.IsLocal)
  307. continue;
  308. if (!delivered.Add(recipient))
  309. continue; // avoid duplicate enqueue if recipients enumerates same gamer twice
  310. var clone = new byte[data.Length];
  311. Buffer.BlockCopy(data, 0, clone, 0, data.Length);
  312. recipient.EnqueueIncomingPacket(clone, this);
  313. }
  314. break;
  315. case NetworkSessionType.PlayerMatch:
  316. // Placeholder for future implementation
  317. throw new NotImplementedException("PlayerMatch session type is not yet supported.");
  318. case NetworkSessionType.Ranked:
  319. // Placeholder for future implementation
  320. throw new NotImplementedException("Ranked session type is not yet supported.");
  321. default:
  322. throw new ArgumentOutOfRangeException(nameof(session.SessionType), $"Unsupported session type: {session.SessionType}");
  323. }
  324. }
  325. internal void EnqueueIncomingPacket(byte[] data, NetworkGamer sender)
  326. {
  327. lock (incomingPackets)
  328. {
  329. incomingPackets.Enqueue((data, sender));
  330. }
  331. }
  332. }
  333. }