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;
107 mNetworkSession.GameStarted += new EventHandler<GameStartedEventArgs>(mNetworkSession_GameStarted);
108 mJoinedSessionDelegate(mNetworkSession, this);
113 void mNetworkSession_GameStarted(object sender, GameStartedEventArgs e)
119 /// Determine whether or not the network game object is associated with any network session.
121 /// <returns>True if there exists a NetworkSession; false otherwise.</returns>
122 public bool HasActiveSession
126 return mNetworkSession != null;
132 /// Find available sessions to join. You should not already be in a session when
133 /// calling this method; call LeaveSession first.
135 /// <param name="callback">The delegate/method to call when the search finishes.</param>
136 public void FindSessions(FoundSessionsDelegate callback)
138 Debug.Assert(mNetworkSession == null);
140 mFoundSessionsDelegate = callback;
141 NetworkSession.BeginFind(NetworkSessionType.SystemLink, 1, null, new AsyncCallback(FindSessionsEnd), null);
143 private void FindSessionsEnd(IAsyncResult result)
145 AvailableNetworkSessionCollection sessions = NetworkSession.EndFind(result);
146 mFoundSessionsDelegate(sessions, this);
150 /// Join a network session found using FindSessions(). This is for joining a game that
151 /// somebody else has already started hosting. You must not already be in a session.
153 /// <param name="availableSession">Pass the session object to try to join.</param>
154 /// <param name="callback">The delegate/method to call when the search finishes.</param>
155 public void JoinSession(AvailableNetworkSession availableSession, JoinedSessionDelegate callback)
157 Debug.Assert(mNetworkSession == null);
159 mJoinedSessionDelegate = callback;
160 NetworkSession.BeginJoin(availableSession, JoinSessionEnd, null);
162 private void JoinSessionEnd(IAsyncResult result)
164 Debug.Assert(mNetworkSession == null);
166 mNetworkSession = NetworkSession.EndJoin(result);
168 mJoinedSessionDelegate(mNetworkSession, this);
169 mJoinedSessionDelegate = null;
174 /// Leave and dispose of any currently associated network session. You will find yourself
175 /// back in the lobby. You must already be in a session to leave it.
177 public void LeaveSession()
179 Debug.Assert(mNetworkSession != null);
181 mNetworkSession.Dispose();
182 mNetworkSession = null;
187 /// Set up the network session to simulate 200ms latency and 10% packet loss.
189 public void SimulateBadNetwork()
191 Debug.Assert(mNetworkSession != null);
193 mNetworkSession.SimulatedLatency = new TimeSpan(0, 0, 0, 0, 200);
194 mNetworkSession.SimulatedPacketLoss = 0.1f;
199 /// Indicate that the game should begin (moving players from the lobby to the game).
200 /// You must call CreateSession() before calling this.
202 public void StartGame()
204 Debug.Assert(mNetworkSession != null && mNetworkSession.IsHost &&
205 mNetworkSession.AllGamers.Count >= mGame.MinimumSupportedPlayers &&
206 mNetworkSession.IsEveryoneReady);
212 /// Indicate that the game should begin. This is like StartGame() without the sanity
213 /// checks. Use this for debugging.
215 public void ForceStartGame()
217 mNetworkSession.StartGame();
218 mNetworkSession.ResetReady();
225 /// Manages the network session and allows either the lobby or game to update.
227 /// <param name="gameTime">Pass the time away.</param>
228 public void Update(GameTime gameTime)
230 if (mNetworkSession == null)
232 mLobby.Update(gameTime, this);
236 mNetworkSession.Update();
237 HandleIncomingPackets();
239 if (mNetworkSession.SessionState == NetworkSessionState.Lobby)
241 mLobby.Update(gameTime, this);
243 else if (mNetworkSession.SessionState == NetworkSessionState.Playing)
245 //TODO reset needs to be called for all players, currently LocalGamerInfo throughs exception for all nonhosts
246 // because in start game reset is only called on hosts games thus other clients never get an updated list
250 //thoughs exeption see TODO above
251 //if (mGame.IsGameOver(LocalGamerInfo) || mGame.IsTerminated(LocalGamerInfo))
253 // // TODO: Should support moving back to the session lobby.
258 if (HaveNeededEvents)
260 if (IsLatencyAdjustmentFrame)
265 mLocalEvents.AddRange(GetEventsFromInput());
268 mGame.Update(mTargetTimeSpan);
274 if (mStallCount % 60 == 0)
276 Console.WriteLine("Stalled for " + mStallCount + " frames.");
279 /*if (mStallCount > StallTimeout)
284 else if (mStallCount == 1)
288 else if (mStallCount % 60 == 0)
297 /// Allows either the lobby or the game to draw, depending on the state
298 /// of the network connection and whether or not a game is in progress.
300 /// <param name="gameTime">Pass the time away.</param>
301 /// <param name="spriteBatch">The sprite batch.</param>
302 public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
304 if (mNetworkSession == null)
306 mLobby.Draw(spriteBatch);
310 if (mNetworkSession.SessionState == NetworkSessionState.Lobby)
312 mLobby.Draw(spriteBatch);
314 else if (mNetworkSession.SessionState == NetworkSessionState.Playing)
316 mGame.Draw(spriteBatch);
323 /// Get the chat messages that have been receive since the last time this
324 /// method was called.
326 /// <returns>List container of the chat messages.</returns>
327 public List<ChatInfo> ReceiveChats()
329 List<ChatInfo> chats = mChatPackets;
330 mChatPackets = new List<ChatInfo>();
335 /// Send a chat message to all gamers in the session. You should already be
336 /// in a session before calling this method.
338 /// <param name="message">The text of the message.</param>
339 public void SendChat(String message)
341 WriteChatPacket(message);
342 LocalGamer.SendData(mPacketWriter, SendDataOptions.ReliableInOrder);
346 /// Send a chat message to a specific gamer in the session. You should already
347 /// be in a session before calling this method.
349 /// <param name="message">The text of the message.</param>
350 /// <param name="recipient">The gamer to receive the message.</param>
351 public void SendChat(String message, NetworkGamer recipient)
353 WriteChatPacket(message);
354 LocalGamer.SendData(mPacketWriter, SendDataOptions.ReliableInOrder, recipient);
360 // Private class variable members
361 #region Instance Variables
363 NetworkSession mNetworkSession;
364 PacketReader mPacketReader = new PacketReader();
365 PacketWriter mPacketWriter = new PacketWriter();
367 JoinedSessionDelegate mJoinedSessionDelegate;
368 FoundSessionsDelegate mFoundSessionsDelegate;
371 IDeterministicGame mGame;
373 List<ChatInfo> mChatPackets = new List<ChatInfo>();
375 List<EventInfo> mLocalEvents = new List<EventInfo>();
376 List<EventInfo> mLastLocalEvents = new List<EventInfo>();
378 List<Keys> mLastPressedKeys = new List<Keys>();
379 bool mLastLeftButtonPressed;
380 bool mLastRightButtonPressed;
381 bool mLastMiddleButtonPressed;
382 int mLastMousePositionX;
383 int mLastMousePositionY;
386 long mNextLatencyAdjustmentFrame;
390 TimeSpan mTargetTimeSpan = new TimeSpan(166666);
391 public TimeSpan TargetTimeSpan
395 return mTargetTimeSpan;
399 Dictionary<byte, GamerInfo> mGamers;
400 GamerInfo[] GamerArray
404 GamerInfo[] gamerList = mGamers.Values.ToArray();
405 Array.Sort(gamerList, delegate(GamerInfo a, GamerInfo b)
407 return a.Gamer.Id.CompareTo(b.Gamer.Id);
412 GamerInfo LocalGamerInfo
416 return mGamers[LocalGamer.Id];
423 // Private types for the implementation of the network protocol
424 #region Private Types
449 abstract class EventInfo
451 public NetworkGamer Gamer;
452 public long FrameOfApplication;
454 public EventInfo(NetworkGamer gamer, long frameNumber)
457 FrameOfApplication = frameNumber;
460 public abstract EventType Id
466 class KeyboardEventInfo : EventInfo
469 public bool IsKeyDown;
471 public KeyboardEventInfo(NetworkGamer gamer, long frameNumber, Keys key, bool isDown)
472 : base(gamer, frameNumber)
478 public override EventType Id
480 get { return IsKeyDown ? EventType.KeyDown : EventType.KeyUp; }
484 class MouseButtonEventInfo : EventInfo
486 public MouseButton Button;
487 public bool IsButtonDown;
489 public MouseButtonEventInfo(NetworkGamer gamer, long frameNumber, MouseButton button, bool isDown)
490 : base(gamer, frameNumber)
493 IsButtonDown = isDown;
496 public override EventType Id
498 get { return IsButtonDown ? EventType.MouseDown : EventType.MouseUp; }
502 class MouseMotionEventInfo : EventInfo
507 public MouseMotionEventInfo(NetworkGamer gamer, long frameNumber, int x, int y)
508 : base(gamer, frameNumber)
514 public override EventType Id
516 get { return EventType.MouseMove; }
522 public NetworkGamer Gamer;
523 public long HighestFrameNumber = 0;
524 public int StallCount = 0;
525 public int AverageOwd = 0;
526 public bool IsWaitedOn = false;
527 public List<EventInfo>[] Events = new List<EventInfo>[MaximumLatency];
529 public GamerInfo(NetworkGamer gamer)
535 const int MaximumLatency = 120;
536 const int StallTimeout = 900;
541 // Private implementation methods of the network protocol
542 #region Private Implementation Methods
545 /// Reinitialize the private variables in preparation for a new game to start.
550 mNextLatencyAdjustmentFrame = 1;
552 mAverageOwd = CurrentAverageOneWayDelay;
554 mGamers = new Dictionary<byte, GamerInfo>();
555 foreach (NetworkGamer gamer in NetworkGamers)
557 mGamers.Add(gamer.Id, new GamerInfo(gamer));
560 mGame.ResetGame(GamerArray, LocalGamerInfo);
564 void HandleIncomingPackets()
566 LocalNetworkGamer localGamer = LocalGamer;
568 while (localGamer.IsDataAvailable)
572 localGamer.ReceiveData(mPacketReader, out sender);
573 GamerInfo senderInfo = mGamers[sender.Id];
575 PacketType packetId = (PacketType)mPacketReader.ReadByte();
578 case PacketType.Chat:
580 short messageLength = mPacketReader.ReadInt16();
581 char[] message = mPacketReader.ReadChars(messageLength);
583 ChatInfo chatPacket = new ChatInfo(sender, new String(message));
584 mChatPackets.Add(chatPacket);
587 case PacketType.Event:
589 short stallCount = mPacketReader.ReadInt16();
590 short averageOwd = mPacketReader.ReadInt16();
591 int frameNumber = mPacketReader.ReadInt32();
592 byte numEvents = mPacketReader.ReadByte();
594 if (frameNumber <= senderInfo.HighestFrameNumber)
596 // we know about all these events, so don't bother reading them
600 for (byte i = 0; i < numEvents; ++i)
602 EventInfo eventInfo = ReadEvent(mPacketReader, sender);
604 if (eventInfo != null && eventInfo.FrameOfApplication < senderInfo.HighestFrameNumber)
606 int index = EventArrayIndex;
607 if (senderInfo.Events[index] == null) senderInfo.Events[index] = new List<EventInfo>();
608 senderInfo.Events[index].Add(eventInfo);
612 senderInfo.StallCount = stallCount;
613 senderInfo.AverageOwd = averageOwd;
614 senderInfo.HighestFrameNumber = frameNumber;
617 case PacketType.Stall:
619 byte numStalledPeers = mPacketReader.ReadByte();
620 byte[] stalledPeers = mPacketReader.ReadBytes(numStalledPeers);
628 Console.WriteLine("Received unknown packet type: " + (int)packetId);
637 get { return (int)(mGame.CurrentFrameNumber % MaximumLatency); }
640 EventInfo ReadEvent(PacketReader packetReader, NetworkGamer sender)
642 EventType eventId = (EventType)packetReader.ReadByte();
643 long frameNumber = packetReader.ReadInt32();
647 case EventType.KeyDown:
649 int keyCode1 = packetReader.ReadInt32();
650 return new KeyboardEventInfo(sender, frameNumber, (Keys)keyCode1, true);
652 case EventType.KeyUp:
654 int keyCode2 = packetReader.ReadInt32();
655 return new KeyboardEventInfo(sender, frameNumber, (Keys)keyCode2, false);
657 case EventType.MouseDown:
659 byte buttonId1 = packetReader.ReadByte();
660 return new MouseButtonEventInfo(sender, frameNumber, (MouseButton)buttonId1, true);
662 case EventType.MouseUp:
664 byte buttonId2 = packetReader.ReadByte();
665 return new MouseButtonEventInfo(sender, frameNumber, (MouseButton)buttonId2, false);
667 case EventType.MouseMove:
669 short x = packetReader.ReadInt16();
670 short y = packetReader.ReadInt16();
671 return new MouseMotionEventInfo(sender, frameNumber, x, y);
675 Console.WriteLine("Received unknown event type: " + (int)eventId);
681 void WriteChatPacket(String message)
683 mPacketWriter.Write((byte)PacketType.Chat);
684 mPacketWriter.Write((short)message.Length);
685 mPacketWriter.Write(message.ToCharArray());
688 void WriteEventPacket(List<EventInfo> events)
690 mPacketWriter.Write((byte)PacketType.Event);
691 mPacketWriter.Write((short)mStallCount);
692 mPacketWriter.Write((short)mAverageOwd);
693 mPacketWriter.Write((int)(mGame.CurrentFrameNumber + mLatency));
694 mPacketWriter.Write((byte)events.Count);
696 foreach (EventInfo eventInfo in events)
698 mPacketWriter.Write((byte)eventInfo.Id);
699 mPacketWriter.Write((int)eventInfo.FrameOfApplication);
701 KeyboardEventInfo keyboardEventInfo = eventInfo as KeyboardEventInfo;
702 if (keyboardEventInfo != null)
704 mPacketWriter.Write((int)keyboardEventInfo.Key);
708 MouseButtonEventInfo mouseButtonEventInfo = eventInfo as MouseButtonEventInfo;
709 if (mouseButtonEventInfo != null)
711 mPacketWriter.Write((byte)mouseButtonEventInfo.Button);
715 MouseMotionEventInfo mouseMotionEventInfo = eventInfo as MouseMotionEventInfo;
716 if (mouseMotionEventInfo != null)
718 mPacketWriter.Write((short)mouseMotionEventInfo.X);
719 mPacketWriter.Write((short)mouseMotionEventInfo.Y);
726 bool IsLatencyAdjustmentFrame
730 return mNextLatencyAdjustmentFrame == mGame.CurrentFrameNumber;
736 Debug.Assert(IsLatencyAdjustmentFrame);
738 int maxStallCount = 0;
739 int maxAverageOwd = 0;
741 foreach (GamerInfo gamerInfo in GamerArray)
743 if (gamerInfo.StallCount > maxStallCount) maxStallCount = gamerInfo.StallCount;
744 if (gamerInfo.AverageOwd > maxAverageOwd) maxAverageOwd = gamerInfo.AverageOwd;
748 int prevLatency = mLatency;
750 if (maxStallCount > 0)
752 mLatency += maxStallCount;
756 mLatency = (int)(0.6 * (double)(mLatency - maxAverageOwd) + 1.0);
760 if (prevLatency != mLatency) Console.WriteLine("Latency readjusted to " + mLatency);
762 if (mLatency < 1) mLatency = 1;
763 if (mLatency > MaximumLatency) mLatency = MaximumLatency;
765 mNextLatencyAdjustmentFrame = mGame.CurrentFrameNumber + mLatency;
766 mAverageOwd = CurrentAverageOneWayDelay;
768 mLastLocalEvents = mLocalEvents;
769 mLocalEvents = new List<EventInfo>();
774 List<EventInfo> GetEventsFromInput()
776 List<EventInfo> events = new List<EventInfo>();
778 // 1. Find the keyboard differences; written by Peter.
780 KeyboardState keyState = Keyboard.GetState();
782 List<Keys> pressedKeys = new List<Keys>();
783 List<Keys> releasedKeys = new List<Keys>();
785 Keys[] pressedKeysArray = keyState.GetPressedKeys();
786 foreach (Keys k in pressedKeysArray)
788 if (!mLastPressedKeys.Contains(k)) pressedKeys.Add(k);
789 else mLastPressedKeys.Remove(k);
792 releasedKeys = mLastPressedKeys;
794 foreach (Keys key in pressedKeys)
796 events.Add(new KeyboardEventInfo(LocalGamer, mGame.CurrentFrameNumber, key, true));
798 foreach (Keys key in releasedKeys)
800 events.Add(new KeyboardEventInfo(LocalGamer, mGame.CurrentFrameNumber, key, false));
803 // 2. Find the mouse differences.
805 MouseState mouseState = Mouse.GetState();
807 bool leftButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
808 if (leftButtonPressed != mLastLeftButtonPressed)
810 events.Add(new MouseButtonEventInfo(LocalGamer, mGame.CurrentFrameNumber, MouseButton.Left, leftButtonPressed));
813 bool rightButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
814 if (rightButtonPressed != mLastRightButtonPressed)
816 events.Add(new MouseButtonEventInfo(LocalGamer, mGame.CurrentFrameNumber, MouseButton.Right, rightButtonPressed));
819 bool middleButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
820 if (middleButtonPressed != mLastMiddleButtonPressed)
822 events.Add(new MouseButtonEventInfo(LocalGamer, mGame.CurrentFrameNumber, MouseButton.Middle, middleButtonPressed));
825 int mousePositionX = mouseState.X;
826 int mousePositionY = mouseState.Y;
827 if (mousePositionX != mLastMousePositionX || mousePositionY != mLastMousePositionY)
829 events.Add(new MouseMotionEventInfo(LocalGamer, mGame.CurrentFrameNumber, mousePositionX, mousePositionY));
832 // 3. Save the current peripheral state.
834 mLastPressedKeys = new List<Keys>(pressedKeysArray);
835 mLastLeftButtonPressed = leftButtonPressed;
836 mLastRightButtonPressed = rightButtonPressed;
837 mLastMiddleButtonPressed = middleButtonPressed;
838 mLastMousePositionX = mousePositionX;
839 mLastMousePositionY = mousePositionY;
844 void SendLocalEvents()
846 SendLocalEvents((NetworkGamer)null);
849 void SendLocalEvents(List<NetworkGamer> recipicents)
851 foreach (NetworkGamer gamer in recipicents)
853 SendLocalEvents(gamer);
857 void SendLocalEvents(NetworkGamer recipient)
859 List<EventInfo> events = new List<EventInfo>(mLocalEvents);
860 events.AddRange(mLastLocalEvents);
862 WriteEventPacket(events);
864 if (recipient != null)
866 LocalGamer.SendData(mPacketWriter, SendDataOptions.Reliable, recipient);
870 LocalGamer.SendData(mPacketWriter, SendDataOptions.None);
875 bool HaveNeededEvents
879 long currentFrame = mGame.CurrentFrameNumber;
881 foreach (GamerInfo gamerInfo in mGamers.Values)
883 if (gamerInfo.HighestFrameNumber < currentFrame) return false;
892 int index = EventArrayIndex;
894 foreach (GamerInfo gamerInfo in GamerArray)
896 if (gamerInfo.Events[index] == null) continue;
898 foreach (EventInfo eventInfo in gamerInfo.Events[index])
900 KeyboardEventInfo keyboardEventInfo = eventInfo as KeyboardEventInfo;
901 if (keyboardEventInfo != null)
903 mGame.ApplyKeyInput(gamerInfo, keyboardEventInfo.Key, keyboardEventInfo.IsKeyDown);
907 MouseButtonEventInfo mouseButtonEventInfo = eventInfo as MouseButtonEventInfo;
908 if (mouseButtonEventInfo != null)
910 mGame.ApplyMouseButtonInput(gamerInfo, mouseButtonEventInfo.IsButtonDown);
914 MouseMotionEventInfo mouseMotionEventInfo = eventInfo as MouseMotionEventInfo;
915 if (mouseMotionEventInfo != null)
917 mGame.ApplyMouseLocationInput(gamerInfo, mouseMotionEventInfo.X, mouseMotionEventInfo.Y);
922 gamerInfo.Events[index] = null;
927 int CurrentAverageOneWayDelay
931 Debug.Assert(mNetworkSession != null);
933 double numRemoteGamersTwice = 2 * mNetworkSession.RemoteGamers.Count;
934 double averageOwd = 0;
936 foreach (NetworkGamer gamer in mNetworkSession.RemoteGamers)
938 TimeSpan timeSpan = gamer.RoundtripTime;
939 averageOwd += timeSpan.TotalMilliseconds;
942 return (int)(averageOwd / numRemoteGamersTwice / 16.6666);