2 // Make sure DEBUG is undefined when turning in the project
3 // or the grader will wonder why it's so laggy.
7 using System.Collections.Generic;
10 using Microsoft.Xna.Framework.Net;
11 using System.Diagnostics;
12 using Microsoft.Xna.Framework.GamerServices;
13 using Microsoft.Xna.Framework.Graphics;
14 using Microsoft.Xna.Framework;
15 using Microsoft.Xna.Framework.Input;
16 using System.Collections;
21 /// A manager class to handle network interactions between peers and
22 /// lobby/game switching.
24 public class NetworkManager
26 // Public methods and properties
27 #region Public Methods
30 /// Called when a session has been created or joined using CreateSession() or JoinSession().
32 /// <param name="session">The new session that was created or joined.</param>
33 /// <param name="networkGame">The NetworkGame that joined the session.</param>
34 public delegate void JoinedSessionDelegate(NetworkSession session, NetworkManager networkGame);
37 /// Called when sessions are found as a result of calling FindSessions().
39 /// <param name="sessions">A container of the available sessions.</param>
40 /// <param name="networkGame">The NetworkGame that searched for the sessions.</param>
41 public delegate void FoundSessionsDelegate(AvailableNetworkSessionCollection sessions, NetworkManager networkGame);
45 /// Called when an exception is thrown during an asynchronous operation.
47 /// <param name="exception">The exception that was thrown.</param>
48 /// <param name="networkGame">The NetworkGame that errored.</param>
49 public delegate void CaughtErrorDelegate(Exception exception, NetworkManager networkGame);
52 /// Get and set the error delegate, called when an exception is thrown during
53 /// and asynchronous operation. This will occur if you try to create or join a
54 /// session without being logged into a profile.
56 public CaughtErrorDelegate ErrorDelegate;
60 /// Construct a NetworkGame with a lobby and a game.
62 /// <param name="lobby">Provides an associated lobby to update and draw.</param>
63 /// <param name="game">Provides a game object to be played over the network.</param>
64 public NetworkManager(IScreenManager lobby, IDeterministicGame game)
66 Debug.Assert(lobby != null && game != null);
74 /// Get the Gamer object for the local player.
76 public LocalNetworkGamer LocalGamer
80 // TODO: Is this the correct way to get the single local gamer?
81 return mNetworkSession.LocalGamers[0];
86 /// Get all the gamers associated with the active network session.
88 public GamerCollection<NetworkGamer> NetworkGamers
92 return mNetworkSession.AllGamers;
98 /// Begin a new network session with the local gamer as the host. You must not
99 /// call this method or use JoinSession without first using LeaveSession.
101 /// <param name="callback">The delegate/method to call when the session is created.</param>
102 public void CreateSession(JoinedSessionDelegate callback)
104 CreateSession(mGame.MaximumSupportedPlayers, callback);
108 /// Begin a new network session with the local gamer as the host. You must not
109 /// call this method or use JoinSession without first using LeaveSession.
111 /// <param name="maxGamers">Provide the maximum number of players allowed to connect.</param>
112 /// <param name="callback">The delegate/method to call when the session is created.</param>
113 public void CreateSession(int maxGamers, JoinedSessionDelegate callback)
115 Debug.Assert(mNetworkSession == null);
117 mJoinedSessionDelegate = callback;
118 NetworkSession.BeginCreate(NetworkSessionType.SystemLink, 1, maxGamers, CreateSessionEnd, null);
120 void CreateSessionEnd(IAsyncResult result)
122 Debug.Assert(mNetworkSession == null);
126 mNetworkSession = NetworkSession.EndCreate(result);
127 mNetworkSession.AllowHostMigration = true;
128 mNetworkSession.AllowJoinInProgress = false;
129 mNetworkSession.GameStarted += new EventHandler<GameStartedEventArgs>(GameStartedEvent);
133 if (ErrorDelegate != null) ErrorDelegate(e, this);
136 mJoinedSessionDelegate(mNetworkSession, this);
137 mJoinedSessionDelegate = null;
139 void GameStartedEvent(object sender, GameStartedEventArgs e)
145 /// Determine whether or not the network game object is associated with any network session.
147 /// <returns>True if there exists a NetworkSession; false otherwise.</returns>
148 public bool HasActiveSession
152 return mNetworkSession != null;
158 /// Find available sessions to join. You should not already be in a session when
159 /// calling this method; call LeaveSession first.
161 /// <param name="callback">The delegate/method to call when the search finishes.</param>
162 public void FindSessions(FoundSessionsDelegate callback)
164 Debug.Assert(mNetworkSession == null);
166 mFoundSessionsDelegate = callback;
167 NetworkSession.BeginFind(NetworkSessionType.SystemLink, 1, null, new AsyncCallback(FindSessionsEnd), null);
169 void FindSessionsEnd(IAsyncResult result)
171 AvailableNetworkSessionCollection sessions;
174 sessions = NetworkSession.EndFind(result);
178 if (ErrorDelegate != null) ErrorDelegate(e, this);
181 mFoundSessionsDelegate(sessions, this);
182 mFoundSessionsDelegate = null;
186 /// Join a network session found using FindSessions(). This is for joining a game that
187 /// somebody else has already started hosting. You must not already be in a session.
189 /// <param name="availableSession">Pass the session object to try to join.</param>
190 /// <param name="callback">The delegate/method to call when the search finishes.</param>
191 public void JoinSession(AvailableNetworkSession availableSession, JoinedSessionDelegate callback)
193 Debug.Assert(mNetworkSession == null);
195 mJoinedSessionDelegate = callback;
196 NetworkSession.BeginJoin(availableSession, JoinSessionEnd, null);
198 void JoinSessionEnd(IAsyncResult result)
200 Debug.Assert(mNetworkSession == null);
204 mNetworkSession = NetworkSession.EndJoin(result);
205 mNetworkSession.GameStarted += new EventHandler<GameStartedEventArgs>(GameStartedEvent);
209 if (ErrorDelegate != null) ErrorDelegate(e, this);
212 mJoinedSessionDelegate(mNetworkSession, this);
213 mJoinedSessionDelegate = null;
218 /// Leave and dispose of any currently associated network session. You will find yourself
219 /// back in the lobby. You must already be in a session to leave it.
221 public void LeaveSession()
223 Debug.Assert(mNetworkSession != null);
225 mNetworkSession.Dispose();
226 mNetworkSession = null;
231 /// Set up the network session to simulate 200ms latency and 10% packet loss.
233 public void SimulateBadNetwork()
235 Debug.Assert(mNetworkSession != null);
237 mNetworkSession.SimulatedLatency = new TimeSpan(0, 0, 0, 0, 200);
238 mNetworkSession.SimulatedPacketLoss = 0.1f;
243 /// Indicate that the game should begin (moving players from the lobby to the game).
244 /// You must call CreateSession() before calling this.
246 public void StartGame()
248 Debug.Assert(mNetworkSession != null && mNetworkSession.IsHost &&
249 mNetworkSession.AllGamers.Count >= mGame.MinimumSupportedPlayers &&
250 mNetworkSession.IsEveryoneReady);
256 /// Indicate that the game should begin. This is like StartGame() without the sanity
257 /// checks. Use this for debugging.
259 public void ForceStartGame()
261 mNetworkSession.StartGame();
262 mNetworkSession.ResetReady();
267 /// Manages the network session and allows either the lobby or game to update.
269 /// <param name="gameTime">Pass the time away.</param>
270 public void Update(GameTime gameTime)
272 if (mNetworkSession == null)
274 mLobby.Update(gameTime, this);
278 mNetworkSession.Update();
279 HandleIncomingPackets();
281 if (mNetworkSession.SessionState == NetworkSessionState.Lobby)
283 mLobby.Update(gameTime, this);
285 else if (mNetworkSession.SessionState == NetworkSessionState.Playing)
287 if (mGame.IsTerminated(LocalGamerInfo))
292 else if (mGame.IsGameOver(LocalGamerInfo))
294 ApplyEvents(LocalGamerInfo, GetEventsFromInput());
295 mGame.Update(mTargetTimeSpan);
299 if (HaveNeededEvents)
301 if (IsLatencyAdjustmentFrame)
304 mLastStallCount = mStallCount;
307 mLocalEvents.AddRange(GetEventsFromInput());
312 Console.WriteLine("HASH: " + mGame.CurrentFrameNumber + "\t" + mGame.CurrentChecksum);
315 mGame.Update(mTargetTimeSpan);
321 // Send a reliable event packet to each stalled gamer.
322 if (mStallCount == 1)
325 Console.WriteLine("STAL: ====");
328 foreach (GamerInfo gamerInfo in GamerArray)
330 if (gamerInfo.HighestFrameNumber < mGame.CurrentFrameNumber)
332 SendLocalEvents(gamerInfo.Gamer);
336 else if (mStallCount > 600)
338 Console.WriteLine("One or more players have stalled excessively. Leaving session...");
347 /// Allows either the lobby or the game to draw, depending on the state
348 /// of the network connection and whether or not a game is in progress.
350 /// <param name="gameTime">Pass the time away.</param>
351 /// <param name="spriteBatch">The sprite batch.</param>
352 public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
354 if (mNetworkSession == null)
356 mLobby.Draw(spriteBatch);
360 if (mNetworkSession.SessionState == NetworkSessionState.Lobby)
362 mLobby.Draw(spriteBatch);
364 else if (mNetworkSession.SessionState == NetworkSessionState.Playing)
367 mGame.Draw(spriteBatch);
374 /// Get the chat messages that have been received since the last time this
375 /// method was called.
377 /// <returns>List container of the chat messages.</returns>
378 public List<ChatInfo> ReceiveChats()
380 List<ChatInfo> chats = mChatPackets;
381 mChatPackets = new List<ChatInfo>();
386 /// Send a chat message to all gamers in the session. You should already be
387 /// in a session before calling this method.
389 /// <param name="message">The text of the message.</param>
390 public void SendChat(String message)
392 WriteChatPacket(message);
393 LocalGamer.SendData(mPacketWriter, SendDataOptions.ReliableInOrder);
397 /// Send a chat message to a specific gamer in the session. You should already
398 /// be in a session before calling this method.
400 /// <param name="message">The text of the message.</param>
401 /// <param name="recipient">The gamer to receive the message.</param>
402 public void SendChat(String message, NetworkGamer recipient)
404 Debug.Assert(recipient != null && !recipient.IsDisposed);
406 WriteChatPacket(message);
407 LocalGamer.SendData(mPacketWriter, SendDataOptions.ReliableInOrder, recipient);
413 // Private class variable members
414 #region Instance Variables
416 NetworkSession mNetworkSession;
417 PacketReader mPacketReader = new PacketReader();
418 PacketWriter mPacketWriter = new PacketWriter();
420 JoinedSessionDelegate mJoinedSessionDelegate;
421 FoundSessionsDelegate mFoundSessionsDelegate;
423 IScreenManager mLobby;
424 IDeterministicGame mGame;
426 List<ChatInfo> mChatPackets = new List<ChatInfo>();
428 List<EventInfo> mLocalEvents = new List<EventInfo>();
429 List<EventInfo> mLastLocalEvents = new List<EventInfo>();
431 List<Keys> mLastPressedKeys = new List<Keys>();
432 bool mLastLeftButtonPressed;
433 bool mLastRightButtonPressed;
434 bool mLastMiddleButtonPressed;
435 int mLastMousePositionX;
436 int mLastMousePositionY;
439 long mHighestFrameNumber;
440 long mNextLatencyAdjustmentFrame;
446 bool mDontSendEvents;
449 TimeSpan mTargetTimeSpan = new TimeSpan(166666);
450 public TimeSpan TargetTimeSpan
454 return mTargetTimeSpan;
458 Dictionary<byte, GamerInfo> mGamers;
459 GamerInfo[] GamerArray
463 GamerInfo[] gamerList = mGamers.Values.ToArray();
464 Array.Sort(gamerList, delegate(GamerInfo a, GamerInfo b)
466 return a.Gamer.Id.CompareTo(b.Gamer.Id);
471 GamerInfo LocalGamerInfo
475 return mGamers[LocalGamer.Id];
482 // Private types for the implementation of the network protocol
483 #region Private Types
507 abstract class EventInfo
509 public NetworkGamer Gamer;
510 public long FrameOfApplication;
512 public EventInfo(NetworkGamer gamer, long frameNumber)
515 FrameOfApplication = frameNumber;
518 public abstract EventType Id
524 class KeyboardEventInfo : EventInfo
527 public bool IsKeyDown;
529 public KeyboardEventInfo(NetworkGamer gamer, long frameNumber, Keys key, bool isDown)
530 : base(gamer, frameNumber)
536 public override EventType Id
538 get { return IsKeyDown ? EventType.KeyDown : EventType.KeyUp; }
542 class MouseButtonEventInfo : EventInfo
544 public MouseButton Button;
545 public bool IsButtonDown;
547 public MouseButtonEventInfo(NetworkGamer gamer, long frameNumber, MouseButton button, bool isDown)
548 : base(gamer, frameNumber)
551 IsButtonDown = isDown;
554 public override EventType Id
556 get { return IsButtonDown ? EventType.MouseDown : EventType.MouseUp; }
560 class MouseMotionEventInfo : EventInfo
565 public MouseMotionEventInfo(NetworkGamer gamer, long frameNumber, int x, int y)
566 : base(gamer, frameNumber)
572 public override EventType Id
574 get { return EventType.MouseMove; }
580 public NetworkGamer Gamer;
581 public long HighestFrameNumber = 0;
582 public int StallCount = 0;
583 public int AverageOwd = 0;
584 public int NextStallCount = 0;
585 public int NextAverageOwd = 0;
586 public bool IsWaitedOn = false;
587 public List<EventInfo>[] Events = new List<EventInfo>[MaximumLatency];
589 public GamerInfo(NetworkGamer gamer)
595 const int MaximumLatency = 120;
596 const int StallTimeout = 900;
601 // Private implementation methods of the network protocol
602 #region Private Implementation Methods
605 /// Reinitialize the private variables in preparation for a new game to start.
610 mHighestFrameNumber = 0;
611 mNextLatencyAdjustmentFrame = 1;
614 mAverageOwd = CurrentAverageOneWayDelay;
616 mGamers = new Dictionary<byte, GamerInfo>();
617 foreach (NetworkGamer gamer in NetworkGamers)
619 mGamers.Add(gamer.Id, new GamerInfo(gamer));
622 mGame.ResetGame(GamerArray, LocalGamerInfo);
626 void HandleIncomingPackets()
628 LocalNetworkGamer localGamer = LocalGamer;
630 while (localGamer.IsDataAvailable)
634 localGamer.ReceiveData(mPacketReader, out sender);
636 PacketType packetId = (PacketType)mPacketReader.ReadByte();
639 case PacketType.Chat:
641 short messageLength = mPacketReader.ReadInt16();
642 char[] message = mPacketReader.ReadChars(messageLength);
644 ChatInfo chatPacket = new ChatInfo(sender, new String(message));
645 mChatPackets.Add(chatPacket);
648 case PacketType.Event:
650 GamerInfo senderInfo = mGamers[sender.Id];
652 int stallCount = mPacketReader.ReadInt16();
653 int averageOwd = mPacketReader.ReadInt16();
654 int frameNumber = mPacketReader.ReadInt32();
655 int numEvents = mPacketReader.ReadByte();
657 if (frameNumber <= mNextLatencyAdjustmentFrame)
659 senderInfo.StallCount = stallCount;
660 senderInfo.AverageOwd = averageOwd;
664 senderInfo.NextStallCount = stallCount;
665 senderInfo.NextAverageOwd = averageOwd;
668 if (frameNumber <= senderInfo.HighestFrameNumber)
671 Console.WriteLine("SKP" + (char)sender.Id + ": " + mGame.CurrentFrameNumber + "\t" + frameNumber + "\t<=\t" + senderInfo.HighestFrameNumber + "\t#" + numEvents);
674 // we know about all these events, so don't bother reading them
679 Console.WriteLine(" GOT" + (char)sender.Id + ": " + mGame.CurrentFrameNumber + "\t" + frameNumber + "\t>\t" + senderInfo.HighestFrameNumber + "\t#" + numEvents);
682 for (int i = 0; i < numEvents; i++)
684 EventInfo eventInfo = ReadEvent(mPacketReader, sender);
686 if (eventInfo != null && eventInfo.FrameOfApplication > senderInfo.HighestFrameNumber)
688 int index = GetEventArrayIndexForFrame(eventInfo.FrameOfApplication);
689 if (senderInfo.Events[index] == null) senderInfo.Events[index] = new List<EventInfo>();
690 senderInfo.Events[index].Add(eventInfo);
694 senderInfo.HighestFrameNumber = frameNumber;
699 Console.WriteLine("Received unknown packet type: " + (int)packetId);
706 int CurrentEventArrayIndex
708 get { return GetEventArrayIndexForFrame(mGame.CurrentFrameNumber); }
711 int GetEventArrayIndexForFrame(long frame)
713 return (int)(frame % MaximumLatency);
716 EventInfo ReadEvent(PacketReader packetReader, NetworkGamer sender)
718 EventType eventId = (EventType)packetReader.ReadByte();
719 long frameNumber = packetReader.ReadInt32();
723 case EventType.KeyDown:
725 Keys keyCode1 = (Keys)packetReader.ReadInt32();
726 return new KeyboardEventInfo(sender, frameNumber, keyCode1, true);
728 case EventType.KeyUp:
730 Keys keyCode2 = (Keys)packetReader.ReadInt32();
731 return new KeyboardEventInfo(sender, frameNumber, keyCode2, false);
733 case EventType.MouseDown:
735 MouseButton buttonId1 = (MouseButton)packetReader.ReadByte();
736 return new MouseButtonEventInfo(sender, frameNumber, buttonId1, true);
738 case EventType.MouseUp:
740 MouseButton buttonId2 = (MouseButton)packetReader.ReadByte();
741 return new MouseButtonEventInfo(sender, frameNumber, buttonId2, false);
743 case EventType.MouseMove:
745 short x = packetReader.ReadInt16();
746 short y = packetReader.ReadInt16();
747 return new MouseMotionEventInfo(sender, frameNumber, x, y);
751 Console.WriteLine("Received unknown event type: " + (int)eventId);
757 void WriteChatPacket(String message)
759 mPacketWriter.Write((byte)PacketType.Chat);
760 mPacketWriter.Write((short)message.Length);
761 mPacketWriter.Write(message.ToCharArray());
764 void WriteEventPacket(List<EventInfo> events, long highestFrameNumber)
766 mPacketWriter.Write((byte)PacketType.Event);
767 mPacketWriter.Write((short)mLastStallCount);
768 mPacketWriter.Write((short)mAverageOwd);
769 mPacketWriter.Write((int)highestFrameNumber);
770 mPacketWriter.Write((byte)events.Count);
772 foreach (EventInfo eventInfo in events)
774 mPacketWriter.Write((byte)eventInfo.Id);
775 mPacketWriter.Write((int)eventInfo.FrameOfApplication);
777 KeyboardEventInfo keyboardEventInfo = eventInfo as KeyboardEventInfo;
778 if (keyboardEventInfo != null)
780 mPacketWriter.Write((int)keyboardEventInfo.Key);
784 MouseButtonEventInfo mouseButtonEventInfo = eventInfo as MouseButtonEventInfo;
785 if (mouseButtonEventInfo != null)
787 mPacketWriter.Write((byte)mouseButtonEventInfo.Button);
791 MouseMotionEventInfo mouseMotionEventInfo = eventInfo as MouseMotionEventInfo;
792 if (mouseMotionEventInfo != null)
794 mPacketWriter.Write((short)mouseMotionEventInfo.X);
795 mPacketWriter.Write((short)mouseMotionEventInfo.Y);
802 bool IsLatencyAdjustmentFrame
806 return mNextLatencyAdjustmentFrame == mGame.CurrentFrameNumber;
812 Debug.Assert(IsLatencyAdjustmentFrame);
817 Console.WriteLine("STL#: " + mGame.CurrentFrameNumber + "\t" + mStallCount);
821 int maxStallCount = 0;
822 int maxAverageOwd = 0;
824 foreach (GamerInfo gamerInfo in GamerArray)
826 if (gamerInfo.StallCount > maxStallCount) maxStallCount = gamerInfo.StallCount;
827 if (gamerInfo.AverageOwd > maxAverageOwd) maxAverageOwd = gamerInfo.AverageOwd;
829 gamerInfo.StallCount = gamerInfo.NextStallCount;
830 gamerInfo.AverageOwd = gamerInfo.NextAverageOwd;
834 int prevLatency = mLatency;
837 if (maxStallCount > 0)
839 mLatency += maxStallCount;
843 mLatency -= (int)(0.6 * (double)(mLatency - maxAverageOwd) + 1.0);
846 if (mLatency < 1) mLatency = 1;
847 if (mLatency > MaximumLatency) mLatency = MaximumLatency;
850 if (prevLatency != mLatency) Console.WriteLine("NLAG: " + mLatency);
853 mNextLatencyAdjustmentFrame = mGame.CurrentFrameNumber + mLatency;
854 mAverageOwd = CurrentAverageOneWayDelay;
856 mLastLocalEvents = mLocalEvents;
857 mLocalEvents = new List<EventInfo>();
862 List<EventInfo> GetEventsFromInput()
864 List<EventInfo> events = new List<EventInfo>();
866 long frameOfApplication = mGame.CurrentFrameNumber + mLatency;
867 if (frameOfApplication <= mHighestFrameNumber) return events;
868 else mHighestFrameNumber = frameOfApplication;
870 // 1. Find the keyboard differences; written by Peter.
872 KeyboardState keyState = Keyboard.GetState();
874 List<Keys> pressedKeys = new List<Keys>();
875 List<Keys> releasedKeys = new List<Keys>();
877 Keys[] pressedKeysArray = keyState.GetPressedKeys();
878 foreach (Keys k in pressedKeysArray)
880 if (!mLastPressedKeys.Contains(k)) pressedKeys.Add(k);
881 else mLastPressedKeys.Remove(k);
884 releasedKeys = mLastPressedKeys;
886 foreach (Keys key in pressedKeys)
888 events.Add(new KeyboardEventInfo(LocalGamer, frameOfApplication, key, true));
890 foreach (Keys key in releasedKeys)
892 events.Add(new KeyboardEventInfo(LocalGamer, frameOfApplication, key, false));
896 if (pressedKeys.Contains(Keys.Escape)) mDontSendEvents = true;
897 if (releasedKeys.Contains(Keys.Escape)) mDontSendEvents = false;
900 // 2. Find the mouse differences.
902 MouseState mouseState = Mouse.GetState();
904 bool leftButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
905 if (leftButtonPressed != mLastLeftButtonPressed)
907 events.Add(new MouseButtonEventInfo(LocalGamer, frameOfApplication, MouseButton.Left, leftButtonPressed));
910 bool rightButtonPressed = mouseState.RightButton == ButtonState.Pressed;
911 if (rightButtonPressed != mLastRightButtonPressed)
913 events.Add(new MouseButtonEventInfo(LocalGamer, frameOfApplication, MouseButton.Right, rightButtonPressed));
916 bool middleButtonPressed = mouseState.MiddleButton == ButtonState.Pressed;
917 if (middleButtonPressed != mLastMiddleButtonPressed)
919 events.Add(new MouseButtonEventInfo(LocalGamer, frameOfApplication, MouseButton.Middle, middleButtonPressed));
922 int mousePositionX = mouseState.X;
923 int mousePositionY = mouseState.Y;
924 if (mousePositionX != mLastMousePositionX || mousePositionY != mLastMousePositionY)
926 events.Add(new MouseMotionEventInfo(LocalGamer, frameOfApplication, mousePositionX, mousePositionY));
929 // 3. Save the current peripheral state.
931 mLastPressedKeys = new List<Keys>(pressedKeysArray);
932 mLastLeftButtonPressed = leftButtonPressed;
933 mLastRightButtonPressed = rightButtonPressed;
934 mLastMiddleButtonPressed = middleButtonPressed;
935 mLastMousePositionX = mousePositionX;
936 mLastMousePositionY = mousePositionY;
941 void SendLocalEvents()
943 SendLocalEvents((NetworkGamer)null);
946 void SendLocalEvents(List<NetworkGamer> recipicents)
948 foreach (NetworkGamer gamer in recipicents)
950 SendLocalEvents(gamer);
954 void SendLocalEvents(NetworkGamer recipient)
957 if (mDontSendEvents) return;
960 List<EventInfo> events = new List<EventInfo>(mLocalEvents);
961 events.AddRange(mLastLocalEvents);
963 if (recipient != null && !recipient.IsDisposed)
965 // if there is a recipient, we are resending old events
966 WriteEventPacket(events, mGame.CurrentFrameNumber - 1);
967 LocalGamer.SendData(mPacketWriter, SendDataOptions.Reliable, recipient);
971 WriteEventPacket(events, mGame.CurrentFrameNumber + mLatency);
972 LocalGamer.SendData(mPacketWriter, SendDataOptions.None);
977 bool HaveNeededEvents
981 long currentFrame = mGame.CurrentFrameNumber;
983 foreach (GamerInfo gamerInfo in mGamers.Values)
985 if (mGame.IsGameOver(gamerInfo)) continue;
986 if (gamerInfo.HighestFrameNumber < currentFrame) return false;
995 int index = CurrentEventArrayIndex;
997 foreach (GamerInfo gamerInfo in GamerArray)
999 if (gamerInfo.Events[index] == null) continue;
1000 ApplyEvents(gamerInfo, gamerInfo.Events[index]);
1001 gamerInfo.Events[index] = null;
1005 void ApplyEvents(GamerInfo gamerInfo, List<EventInfo> events)
1007 foreach (EventInfo eventInfo in events)
1009 KeyboardEventInfo keyboardEventInfo = eventInfo as KeyboardEventInfo;
1010 if (keyboardEventInfo != null)
1013 Console.WriteLine(" KEY: " + keyboardEventInfo.FrameOfApplication + "\t" + keyboardEventInfo.Key + "," + keyboardEventInfo.IsKeyDown);
1016 mGame.ApplyKeyInput(gamerInfo, keyboardEventInfo.Key, keyboardEventInfo.IsKeyDown);
1020 MouseButtonEventInfo mouseButtonEventInfo = eventInfo as MouseButtonEventInfo;
1021 if (mouseButtonEventInfo != null)
1024 Console.WriteLine(" BTN: " + mouseButtonEventInfo.FrameOfApplication + "\t" + mouseButtonEventInfo.IsButtonDown);
1027 mGame.ApplyMouseButtonInput(gamerInfo, mouseButtonEventInfo.IsButtonDown);
1031 MouseMotionEventInfo mouseMotionEventInfo = eventInfo as MouseMotionEventInfo;
1032 if (mouseMotionEventInfo != null)
1035 Console.WriteLine(" MMV: " + mouseMotionEventInfo.FrameOfApplication + "\t" + mouseMotionEventInfo.X + "," + mouseMotionEventInfo.Y);
1038 mGame.ApplyMouseLocationInput(gamerInfo, mouseMotionEventInfo.X, mouseMotionEventInfo.Y);
1045 int CurrentAverageOneWayDelay
1049 Debug.Assert(mNetworkSession != null);
1051 double numRemoteGamersTwice = 2 * mNetworkSession.RemoteGamers.Count;
1052 double averageOwd = 0;
1054 foreach (NetworkGamer gamer in mNetworkSession.RemoteGamers)
1056 TimeSpan timeSpan = gamer.RoundtripTime;
1057 averageOwd += timeSpan.TotalMilliseconds;
1060 return (int)((averageOwd / numRemoteGamersTwice) / 16.6666);