2 using System.Collections.Generic;
5 using Microsoft.Xna.Framework.Net;
6 using System.Diagnostics;
7 using Microsoft.Xna.Framework.GamerServices;
8 using Microsoft.Xna.Framework.Graphics;
9 using Microsoft.Xna.Framework;
10 using Microsoft.Xna.Framework.Input;
11 using System.Collections;
13 namespace CS_3505_Project_06
16 /// A manager class to handle network interactions between peers and
17 /// lobby/game switching.
19 public class NetworkGame
21 // Public methods and properties
22 #region Public Methods
25 /// Called when a session has been created or joined using CreateSession() or JoinSession().
27 /// <param name="session">The new session that was created or joined.</param>
28 /// <param name="networkGame">The NetworkGame that joined the session.</param>
29 public delegate void JoinedSessionDelegate(NetworkSession session, NetworkGame networkGame);
32 /// Called when sessions are found as a result of calling FindSessions().
34 /// <param name="sessions">A container of the available sessions.</param>
35 /// <param name="networkGame">The NetworkGame that searched for the sessions.</param>
36 public delegate void FoundSessionsDelegate(AvailableNetworkSessionCollection sessions, NetworkGame networkGame);
40 /// Construct a NetworkGame with a lobby and a game.
42 /// <param name="lobby">Provides an associated lobby to update and draw.</param>
43 /// <param name="game">Provides a game object to be played over the network.</param>
44 public NetworkGame(ILobby lobby, IDeterministicGame game)
46 Debug.Assert(lobby != null && game != null);
54 /// Get the Gamer object for the local player.
56 public LocalNetworkGamer LocalGamer
60 // TODO: Is this the correct way to get the single local gamer?
61 return mNetworkSession.LocalGamers[0];
66 /// Get all the gamers associated with the active network session.
68 public GamerCollection<NetworkGamer> NetworkGamers
72 return mNetworkSession.AllGamers;
78 /// Begin a new network session with the local gamer as the host. You must not
79 /// call this method or use JoinSession without first using LeaveSession.
81 /// <param name="callback">The delegate/method to call when the session is created.</param>
82 public void CreateSession(JoinedSessionDelegate callback)
84 CreateSession(mGame.MaximumSupportedPlayers, callback);
88 /// Begin a new network session with the local gamer as the host. You must not
89 /// call this method or use JoinSession without first using LeaveSession.
91 /// <param name="maxGamers">Provide the maximum number of players allowed to connect.</param>
92 /// <param name="callback">The delegate/method to call when the session is created.</param>
93 public void CreateSession(int maxGamers, JoinedSessionDelegate callback)
95 Debug.Assert(mNetworkSession == null);
97 mJoinedSessionDelegate = callback;
98 NetworkSession.BeginCreate(NetworkSessionType.SystemLink, 1, maxGamers, CreateSessionEnd, null);
100 private void CreateSessionEnd(IAsyncResult result)
102 Debug.Assert(mNetworkSession == null);
104 mNetworkSession = NetworkSession.EndCreate(result);
105 mNetworkSession.AllowHostMigration = true;
106 mNetworkSession.AllowJoinInProgress = false;
108 mJoinedSessionDelegate(mNetworkSession, this);
112 /// Determine whether or not the network game object is associated with any network session.
114 /// <returns>True if there exists a NetworkSession; false otherwise.</returns>
115 public bool HasActiveSession
119 return mNetworkSession != null;
125 /// Find available sessions to join. You should not already be in a session when
126 /// calling this method; call LeaveSession first.
128 /// <param name="callback">The delegate/method to call when the search finishes.</param>
129 public void FindSessions(FoundSessionsDelegate callback)
131 Debug.Assert(mNetworkSession == null);
133 mFoundSessionsDelegate = callback;
134 NetworkSession.BeginFind(NetworkSessionType.SystemLink, 1, null, new AsyncCallback(FindSessionsEnd), null);
136 private void FindSessionsEnd(IAsyncResult result)
138 AvailableNetworkSessionCollection sessions = NetworkSession.EndFind(result);
139 mFoundSessionsDelegate(sessions, this);
143 /// Join a network session found using FindSessions(). This is for joining a game that
144 /// somebody else has already started hosting. You must not already be in a session.
146 /// <param name="availableSession">Pass the session object to try to join.</param>
147 /// <param name="callback">The delegate/method to call when the search finishes.</param>
148 public void JoinSession(AvailableNetworkSession availableSession, JoinedSessionDelegate callback)
150 Debug.Assert(mNetworkSession == null);
152 mJoinedSessionDelegate = callback;
153 NetworkSession.BeginJoin(availableSession, JoinSessionEnd, null);
155 private void JoinSessionEnd(IAsyncResult result)
157 Debug.Assert(mNetworkSession == null);
159 mNetworkSession = NetworkSession.EndJoin(result);
161 mJoinedSessionDelegate(mNetworkSession, this);
162 mJoinedSessionDelegate = null;
167 /// Leave and dispose of any currently associated network session. You will find yourself
168 /// back in the lobby. You must already be in a session to leave it.
170 public void LeaveSession()
172 Debug.Assert(mNetworkSession != null);
174 mNetworkSession.Dispose();
175 mNetworkSession = null;
180 /// Set up the network session to simulate 200ms latency and 10% packet loss.
182 public void SimulateBadNetwork()
184 Debug.Assert(mNetworkSession != null);
186 mNetworkSession.SimulatedLatency = new TimeSpan(0, 0, 0, 0, 200);
187 mNetworkSession.SimulatedPacketLoss = 0.1f;
192 /// Indicate that the game should begin (moving players from the lobby to the game).
193 /// You must call CreateSession() before calling this.
195 public void StartGame()
197 Debug.Assert(mNetworkSession != null && mNetworkSession.IsHost &&
198 mNetworkSession.AllGamers.Count >= mGame.MinimumSupportedPlayers &&
199 mNetworkSession.IsEveryoneReady);
205 /// Indicate that the game should begin. This is like StartGame() without the sanity
206 /// checks. Use this for debugging.
208 public void ForceStartGame()
210 mNetworkSession.StartGame();
211 mNetworkSession.ResetReady();
218 /// Manages the network session and allows either the lobby or game to update.
220 /// <param name="gameTime">Pass the time away.</param>
221 public void Update(GameTime gameTime)
223 if (mNetworkSession == null)
225 mLobby.Update(gameTime, this);
229 mNetworkSession.Update();
230 HandleIncomingPackets();
232 if (mNetworkSession.SessionState == NetworkSessionState.Lobby)
234 mLobby.Update(gameTime, this);
236 else if (mNetworkSession.SessionState == NetworkSessionState.Playing)
238 if (mGame.IsGameOver(LocalGamerInfo) || mGame.IsTerminated(LocalGamerInfo))
240 // TODO: Should support moving back to the session lobby.
245 if (HaveNeededEvents)
247 if (IsLatencyAdjustmentFrame)
252 mLocalEvents.AddRange(GetEventsFromInput());
255 mGame.Update(mTargetTimeSpan);
261 if (mStallCount % 60 == 0)
263 Console.WriteLine("Stalled for " + mStallCount + " frames.");
266 /*if (mStallCount > StallTimeout)
271 else if (mStallCount == 1)
275 else if (mStallCount % 60 == 0)
284 /// Allows either the lobby or the game to draw, depending on the state
285 /// of the network connection and whether or not a game is in progress.
287 /// <param name="gameTime">Pass the time away.</param>
288 /// <param name="spriteBatch">The sprite batch.</param>
289 public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
291 if (mNetworkSession == null)
293 mLobby.Draw(spriteBatch);
297 if (mNetworkSession.SessionState == NetworkSessionState.Lobby)
299 mLobby.Draw(spriteBatch);
301 else if (mNetworkSession.SessionState == NetworkSessionState.Playing)
303 mGame.Draw(spriteBatch);
310 /// Get the chat messages that have been receive since the last time this
311 /// method was called.
313 /// <returns>List container of the chat messages.</returns>
314 public List<ChatInfo> ReceiveChats()
316 List<ChatInfo> chats = mChatPackets;
317 mChatPackets = new List<ChatInfo>();
322 /// Send a chat message to all gamers in the session. You should already be
323 /// in a session before calling this method.
325 /// <param name="message">The text of the message.</param>
326 public void SendChat(String message)
328 WriteChatPacket(message);
329 LocalGamer.SendData(mPacketWriter, SendDataOptions.ReliableInOrder);
333 /// Send a chat message to a specific gamer in the session. You should already
334 /// be in a session before calling this method.
336 /// <param name="message">The text of the message.</param>
337 /// <param name="recipient">The gamer to receive the message.</param>
338 public void SendChat(String message, NetworkGamer recipient)
340 WriteChatPacket(message);
341 LocalGamer.SendData(mPacketWriter, SendDataOptions.ReliableInOrder, recipient);
347 // Private class variable members
348 #region Instance Variables
350 NetworkSession mNetworkSession;
351 PacketReader mPacketReader = new PacketReader();
352 PacketWriter mPacketWriter = new PacketWriter();
354 JoinedSessionDelegate mJoinedSessionDelegate;
355 FoundSessionsDelegate mFoundSessionsDelegate;
358 IDeterministicGame mGame;
360 List<ChatInfo> mChatPackets = new List<ChatInfo>();
362 List<EventInfo> mLocalEvents = new List<EventInfo>();
363 List<EventInfo> mLastLocalEvents = new List<EventInfo>();
365 List<Keys> mLastPressedKeys = new List<Keys>();
366 bool mLastLeftButtonPressed;
367 bool mLastRightButtonPressed;
368 bool mLastMiddleButtonPressed;
369 int mLastMousePositionX;
370 int mLastMousePositionY;
373 long mNextLatencyAdjustmentFrame;
377 TimeSpan mTargetTimeSpan = new TimeSpan(166666);
378 public TimeSpan TargetTimeSpan
382 return mTargetTimeSpan;
386 Dictionary<byte, GamerInfo> mGamers;
387 GamerInfo[] GamerArray
391 GamerInfo[] gamerList = mGamers.Values.ToArray();
392 Array.Sort(gamerList, delegate(GamerInfo a, GamerInfo b)
394 return a.Gamer.Id.CompareTo(b.Gamer.Id);
399 GamerInfo LocalGamerInfo
403 return mGamers[LocalGamer.Id];
410 // Private types for the implementation of the network protocol
411 #region Private Types
436 abstract class EventInfo
438 public NetworkGamer Gamer;
439 public long FrameOfApplication;
441 public EventInfo(NetworkGamer gamer, long frameNumber)
444 FrameOfApplication = frameNumber;
447 public abstract EventType Id
453 class KeyboardEventInfo : EventInfo
456 public bool IsKeyDown;
458 public KeyboardEventInfo(NetworkGamer gamer, long frameNumber, Keys key, bool isDown)
459 : base(gamer, frameNumber)
465 public override EventType Id
467 get { return IsKeyDown ? EventType.KeyDown : EventType.KeyUp; }
471 class MouseButtonEventInfo : EventInfo
473 public MouseButton Button;
474 public bool IsButtonDown;
476 public MouseButtonEventInfo(NetworkGamer gamer, long frameNumber, MouseButton button, bool isDown)
477 : base(gamer, frameNumber)
480 IsButtonDown = isDown;
483 public override EventType Id
485 get { return IsButtonDown ? EventType.MouseDown : EventType.MouseUp; }
489 class MouseMotionEventInfo : EventInfo
494 public MouseMotionEventInfo(NetworkGamer gamer, long frameNumber, int x, int y)
495 : base(gamer, frameNumber)
501 public override EventType Id
503 get { return EventType.MouseMove; }
509 public NetworkGamer Gamer;
510 public long HighestFrameNumber = 0;
511 public int StallCount = 0;
512 public int AverageOwd = 0;
513 public bool IsWaitedOn = false;
514 public List<EventInfo>[] Events = new List<EventInfo>[MaximumLatency];
516 public GamerInfo(NetworkGamer gamer)
522 const int MaximumLatency = 120;
523 const int StallTimeout = 900;
528 // Private implementation methods of the network protocol
529 #region Private Implementation Methods
532 /// Reinitialize the private variables in preparation for a new game to start.
537 mNextLatencyAdjustmentFrame = 1;
539 mAverageOwd = CurrentAverageOneWayDelay;
541 mGamers = new Dictionary<byte, GamerInfo>();
542 foreach (NetworkGamer gamer in NetworkGamers)
544 mGamers.Add(gamer.Id, new GamerInfo(gamer));
547 mGame.ResetGame(GamerArray, LocalGamerInfo);
551 void HandleIncomingPackets()
553 LocalNetworkGamer localGamer = LocalGamer;
555 while (localGamer.IsDataAvailable)
559 localGamer.ReceiveData(mPacketReader, out sender);
560 GamerInfo senderInfo = mGamers[sender.Id];
562 PacketType packetId = (PacketType)mPacketReader.ReadByte();
565 case PacketType.Chat:
567 short messageLength = mPacketReader.ReadInt16();
568 char[] message = mPacketReader.ReadChars(messageLength);
570 ChatInfo chatPacket = new ChatInfo(sender, new String(message));
571 mChatPackets.Add(chatPacket);
574 case PacketType.Event:
576 short stallCount = mPacketReader.ReadInt16();
577 short averageOwd = mPacketReader.ReadInt16();
578 int frameNumber = mPacketReader.ReadInt32();
579 byte numEvents = mPacketReader.ReadByte();
581 if (frameNumber <= senderInfo.HighestFrameNumber)
583 // we know about all these events, so don't bother reading them
587 for (byte i = 0; i < numEvents; ++i)
589 EventInfo eventInfo = ReadEvent(mPacketReader, sender);
591 if (eventInfo != null && eventInfo.FrameOfApplication < senderInfo.HighestFrameNumber)
593 int index = EventArrayIndex;
594 if (senderInfo.Events[index] == null) senderInfo.Events[index] = new List<EventInfo>();
595 senderInfo.Events[index].Add(eventInfo);
599 senderInfo.StallCount = stallCount;
600 senderInfo.AverageOwd = averageOwd;
601 senderInfo.HighestFrameNumber = frameNumber;
604 case PacketType.Stall:
606 byte numStalledPeers = mPacketReader.ReadByte();
607 byte[] stalledPeers = mPacketReader.ReadBytes(numStalledPeers);
615 Console.WriteLine("Received unknown packet type: " + (int)packetId);
624 get { return (int)(mGame.CurrentFrameNumber % MaximumLatency); }
627 EventInfo ReadEvent(PacketReader packetReader, NetworkGamer sender)
629 EventType eventId = (EventType)packetReader.ReadByte();
630 long frameNumber = packetReader.ReadInt32();
634 case EventType.KeyDown:
636 int keyCode1 = packetReader.ReadInt32();
637 return new KeyboardEventInfo(sender, frameNumber, (Keys)keyCode1, true);
639 case EventType.KeyUp:
641 int keyCode2 = packetReader.ReadInt32();
642 return new KeyboardEventInfo(sender, frameNumber, (Keys)keyCode2, false);
644 case EventType.MouseDown:
646 byte buttonId1 = packetReader.ReadByte();
647 return new MouseButtonEventInfo(sender, frameNumber, (MouseButton)buttonId1, true);
649 case EventType.MouseUp:
651 byte buttonId2 = packetReader.ReadByte();
652 return new MouseButtonEventInfo(sender, frameNumber, (MouseButton)buttonId2, false);
654 case EventType.MouseMove:
656 short x = packetReader.ReadInt16();
657 short y = packetReader.ReadInt16();
658 return new MouseMotionEventInfo(sender, frameNumber, x, y);
662 Console.WriteLine("Received unknown event type: " + (int)eventId);
668 void WriteChatPacket(String message)
670 mPacketWriter.Write((byte)PacketType.Chat);
671 mPacketWriter.Write((short)message.Length);
672 mPacketWriter.Write(message.ToCharArray());
675 void WriteEventPacket(List<EventInfo> events)
677 mPacketWriter.Write((byte)PacketType.Event);
678 mPacketWriter.Write((short)mStallCount);
679 mPacketWriter.Write((short)mAverageOwd);
680 mPacketWriter.Write((int)(mGame.CurrentFrameNumber + mLatency));
681 mPacketWriter.Write((byte)events.Count);
683 foreach (EventInfo eventInfo in events)
685 mPacketWriter.Write((byte)eventInfo.Id);
686 mPacketWriter.Write((int)eventInfo.FrameOfApplication);
688 KeyboardEventInfo keyboardEventInfo = eventInfo as KeyboardEventInfo;
689 if (keyboardEventInfo != null)
691 mPacketWriter.Write((int)keyboardEventInfo.Key);
695 MouseButtonEventInfo mouseButtonEventInfo = eventInfo as MouseButtonEventInfo;
696 if (mouseButtonEventInfo != null)
698 mPacketWriter.Write((byte)mouseButtonEventInfo.Button);
702 MouseMotionEventInfo mouseMotionEventInfo = eventInfo as MouseMotionEventInfo;
703 if (mouseMotionEventInfo != null)
705 mPacketWriter.Write((short)mouseMotionEventInfo.X);
706 mPacketWriter.Write((short)mouseMotionEventInfo.Y);
713 bool IsLatencyAdjustmentFrame
717 return mNextLatencyAdjustmentFrame == mGame.CurrentFrameNumber;
723 Debug.Assert(IsLatencyAdjustmentFrame);
725 int maxStallCount = 0;
726 int maxAverageOwd = 0;
728 foreach (GamerInfo gamerInfo in GamerArray)
730 if (gamerInfo.StallCount > maxStallCount) maxStallCount = gamerInfo.StallCount;
731 if (gamerInfo.AverageOwd > maxAverageOwd) maxAverageOwd = gamerInfo.AverageOwd;
735 int prevLatency = mLatency;
737 if (maxStallCount > 0)
739 mLatency += maxStallCount;
743 mLatency = (int)(0.6 * (double)(mLatency - maxAverageOwd) + 1.0);
747 if (prevLatency != mLatency) Console.WriteLine("Latency readjusted to " + mLatency);
749 if (mLatency < 1) mLatency = 1;
750 if (mLatency > MaximumLatency) mLatency = MaximumLatency;
752 mNextLatencyAdjustmentFrame = mGame.CurrentFrameNumber + mLatency;
753 mAverageOwd = CurrentAverageOneWayDelay;
755 mLastLocalEvents = mLocalEvents;
756 mLocalEvents = new List<EventInfo>();
761 List<EventInfo> GetEventsFromInput()
763 List<EventInfo> events = new List<EventInfo>();
765 // 1. Find the keyboard differences; written by Peter.
767 KeyboardState keyState = Keyboard.GetState();
769 List<Keys> pressedKeys = new List<Keys>();
770 List<Keys> releasedKeys = new List<Keys>();
772 Keys[] pressedKeysArray = keyState.GetPressedKeys();
773 foreach (Keys k in pressedKeysArray)
775 if (!mLastPressedKeys.Contains(k)) pressedKeys.Add(k);
776 else mLastPressedKeys.Remove(k);
779 releasedKeys = mLastPressedKeys;
781 foreach (Keys key in pressedKeys)
783 events.Add(new KeyboardEventInfo(LocalGamer, mGame.CurrentFrameNumber, key, true));
785 foreach (Keys key in releasedKeys)
787 events.Add(new KeyboardEventInfo(LocalGamer, mGame.CurrentFrameNumber, key, false));
790 // 2. Find the mouse differences.
792 MouseState mouseState = Mouse.GetState();
794 bool leftButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
795 if (leftButtonPressed != mLastLeftButtonPressed)
797 events.Add(new MouseButtonEventInfo(LocalGamer, mGame.CurrentFrameNumber, MouseButton.Left, leftButtonPressed));
800 bool rightButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
801 if (rightButtonPressed != mLastRightButtonPressed)
803 events.Add(new MouseButtonEventInfo(LocalGamer, mGame.CurrentFrameNumber, MouseButton.Right, rightButtonPressed));
806 bool middleButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
807 if (middleButtonPressed != mLastMiddleButtonPressed)
809 events.Add(new MouseButtonEventInfo(LocalGamer, mGame.CurrentFrameNumber, MouseButton.Middle, middleButtonPressed));
812 int mousePositionX = mouseState.X;
813 int mousePositionY = mouseState.Y;
814 if (mousePositionX != mLastMousePositionX || mousePositionY != mLastMousePositionY)
816 events.Add(new MouseMotionEventInfo(LocalGamer, mGame.CurrentFrameNumber, mousePositionX, mousePositionY));
819 // 3. Save the current peripheral state.
821 mLastPressedKeys = new List<Keys>(pressedKeysArray);
822 mLastLeftButtonPressed = leftButtonPressed;
823 mLastRightButtonPressed = rightButtonPressed;
824 mLastMiddleButtonPressed = middleButtonPressed;
825 mLastMousePositionX = mousePositionX;
826 mLastMousePositionY = mousePositionY;
831 void SendLocalEvents()
833 SendLocalEvents((NetworkGamer)null);
836 void SendLocalEvents(List<NetworkGamer> recipicents)
838 foreach (NetworkGamer gamer in recipicents)
840 SendLocalEvents(gamer);
844 void SendLocalEvents(NetworkGamer recipient)
846 List<EventInfo> events = new List<EventInfo>(mLocalEvents);
847 events.AddRange(mLastLocalEvents);
849 WriteEventPacket(events);
851 if (recipient != null)
853 LocalGamer.SendData(mPacketWriter, SendDataOptions.Reliable, recipient);
857 LocalGamer.SendData(mPacketWriter, SendDataOptions.None);
862 bool HaveNeededEvents
866 long currentFrame = mGame.CurrentFrameNumber;
868 foreach (GamerInfo gamerInfo in mGamers.Values)
870 if (gamerInfo.HighestFrameNumber < currentFrame) return false;
879 int index = EventArrayIndex;
881 foreach (GamerInfo gamerInfo in GamerArray)
883 if (gamerInfo.Events[index] == null) continue;
885 foreach (EventInfo eventInfo in gamerInfo.Events[index])
887 KeyboardEventInfo keyboardEventInfo = eventInfo as KeyboardEventInfo;
888 if (keyboardEventInfo != null)
890 mGame.ApplyKeyInput(gamerInfo, keyboardEventInfo.Key, keyboardEventInfo.IsKeyDown);
894 MouseButtonEventInfo mouseButtonEventInfo = eventInfo as MouseButtonEventInfo;
895 if (mouseButtonEventInfo != null)
897 mGame.ApplyMouseButtonInput(gamerInfo, mouseButtonEventInfo.IsButtonDown);
901 MouseMotionEventInfo mouseMotionEventInfo = eventInfo as MouseMotionEventInfo;
902 if (mouseMotionEventInfo != null)
904 mGame.ApplyMouseLocationInput(gamerInfo, mouseMotionEventInfo.X, mouseMotionEventInfo.Y);
909 gamerInfo.Events[index] = null;
914 int CurrentAverageOneWayDelay
918 Debug.Assert(mNetworkSession != null);
920 double numRemoteGamersTwice = 2 * mNetworkSession.RemoteGamers.Count;
921 double averageOwd = 0;
923 foreach (NetworkGamer gamer in mNetworkSession.RemoteGamers)
925 TimeSpan timeSpan = gamer.RoundtripTime;
926 averageOwd += timeSpan.TotalMilliseconds;
929 return (int)(averageOwd / numRemoteGamersTwice / 16.6666);