private async Task DirectCall(IServerStreamWriter <PlayerUpdate> stream, PlayerUpdate message) { try { await stream.WriteAsync(message); //TotalMessages++; //Console.WriteLine($"Total Messages: {TotalMessages} Connections:{Connections}"); } catch (Exception) { PlayerSubscriberStream.Remove(stream); } }
public ServerUpdatePacket(Packet packet) : base(packet) { DataPacketIds = new HashSet <ServerPacketId>(); HelloServer = new HelloServer(); PlayerUpdate = new PlayerUpdate(); EntityUpdates = new PacketDataCollection <EntityUpdate>(); PlayerEnterScene = new ServerPlayerEnterScene(); PlayerTeamUpdate = new ServerPlayerTeamUpdate(); PlayerSkinUpdate = new ServerPlayerSkinUpdate(); PlayerEmoteUpdate = new ServerPlayerEmoteUpdate(); }
private void UpdateServer(Vector2 move, bool pickUp) { PlayerUpdate update = new PlayerUpdate { Time = DateTime.UtcNow, UserID = ConnectionManager.Instance.UserID, MoveX = move.x, MoveY = move.y, Facing = _facing, PickUp = pickUp, }; Socket.Instance.SendPacket(update, Packets.PlayerUpdate); _inputBuffer[InputBufferIndex++] = update; }
public void NewUpdateReceived(PlayerUpdate value) { UpdateInfo(value); if (playerInfo != null) { playerInfo.updateInfo.playerNameColor = value.playerNameColor; playerInfo.updateInfo.playerState = value.playerState; playerInfo.updateInfo.fullBodyTracking = value.fullBodyTracking; playerInfo.updateInfo.playerScore = value.playerScore; playerInfo.updateInfo.playerCutBlocks = value.playerCutBlocks; playerInfo.updateInfo.playerComboBlocks = value.playerComboBlocks; playerInfo.updateInfo.playerTotalBlocks = value.playerTotalBlocks; playerInfo.updateInfo.playerEnergy = value.playerEnergy; playerInfo.updateInfo.playerLevelOptions = value.playerLevelOptions; } }
// These routines handle the communication between the game peers. public void SendPlayerUpdate(PlayerUpdate update, ShotUpdate shotUpdate) { if (inSession) { NetworkPacket packet = new NetworkPacket(); packet.Write((byte)MessageType.PlayerUpdateID); packet.Write(update); for (int i = 0; i < Constants.NumShots; i++) { packet.Write(shotUpdate.ShotPosition[i]); packet.Write(shotUpdate.ShotAge[i]); } peerObject.SendTo((int)PlayerID.AllPlayers, packet, 0, SendFlags.NoComplete | SendFlags.NoLoopback); } }
private void AreaChanged(AreaInstance area) { try { entityCollectSettingsContainer.Break = true; var dataLocalPlayer = gameController.Game.IngameState.Data.LocalPlayer; if (Player == null) { if (dataLocalPlayer.Path.StartsWith("Meta")) { Player = dataLocalPlayer; Player.IsValid = true; PlayerUpdate?.Invoke(this, Player); } } else { if (Player.Address != dataLocalPlayer.Address) { if (dataLocalPlayer.Path.StartsWith("Meta")) { Player = dataLocalPlayer; Player.IsValid = true; PlayerUpdate?.Invoke(this, Player); } } } entityCache.Clear(); OnlyValidEntities.Clear(); NotOnlyValidEntities.Clear(); foreach (var e in ValidEntitiesByType) { e.Value.Clear(); } // foreach (var e in NotValidEntitiesByType) e.Value.Clear(); } catch (Exception e) { DebugWindow.LogError($"{nameof(EntityListWrapper)} -> {e}"); } }
public async Task PostUser_Async() { PlayerUpdate playerUpdate = new PlayerUpdate() { userId = this.username, money = GameManager.instance.playerPoints }; var data = JsonUtility.ToJson(playerUpdate); HttpContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json"); var response = await client.PostAsync(baseURL + "updateplayer", content); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); Debug.Log(result.ToString()); } }
public void Start() { Plugin.log.Debug($"Player controller created!"); voipSource = gameObject.AddComponent <AudioSource>(); _voipClip = AudioClip.Create("VoIP Clip", 161280, 1, 16000, false); voipSource.clip = _voipClip; voipSource.spatialize = Config.Instance.SpatialAudio; voipSource.loop = true; if (playerInfo != null) { Plugin.log.Debug($"Starting player controller for {playerInfo.playerName}:{playerInfo.playerId}..."); _syncStartInfo = playerInfo.updateInfo; _syncStartInfo = playerInfo.updateInfo; } }
public void Start() { Plugin.log.Debug($"Player controller created!"); voipSource = gameObject.AddComponent <AudioSource>(); voipSource.clip = null; voipSource.spatialize = Config.Instance.SpatialAudio; voipSource.loop = true; voipSource.Play(); if (playerInfo != null) { Plugin.log.Debug($"Starting player controller for {playerInfo.playerName}:{playerInfo.playerId}..."); _syncStartInfo = playerInfo.updateInfo; _syncEndInfo = playerInfo.updateInfo; } }
public Task UpdateAsync(Guid id, PlayerUpdate update) { if (id == Guid.Empty) { throw new ArgumentException("Player id must be provided.", nameof(id)); } if (update == null) { throw new ArgumentNullException(nameof(update), "Update must be provided."); } Logger.LogDebug($"Updating player '{id}' in '{MetadataResolver.TableName<PlayerSql>()}' table."); return(DbConnection.Update <PlayerSql>() .Where(p => p.Id == id) .Set(p => p.Number, update.Number) .Set(p => p.Position, update.Position) .Set(p => p.Status, update.Status) .ExecuteAsync()); }
public static string Change(PlayerUpdate update) { return(update switch { (_, _)s when s.FromPlayer == null && s.ToPlayer == null => null, (_, _)s when s.FromPlayer == null && s.ToPlayer == null => null, (_, _)s when s.FromPlayer.News == null && s.ToPlayer.News == null => null, (PlayerStatuses.Doubtful, PlayerStatuses.Doubtful) s when ChanceOfPlayingChange(s) > 0 => "📈️ Increased chance of playing", (PlayerStatuses.Doubtful, PlayerStatuses.Doubtful) s when ChanceOfPlayingChange(s) < 0 => "📉️ Decreased chance of playing", (PlayerStatuses.Doubtful, PlayerStatuses.Doubtful) s when NewsAdded(s) => "ℹ️ News update", (_, _)s when s.ToPlayer.News.Contains("Self-isolating", StringComparison.InvariantCultureIgnoreCase) => "🦇 COVID-19 🦇", (_, _)s when s.FromPlayer.Status == s.ToPlayer.Status => null, (_, _)s when s.FromPlayer == null => "👋 New player!", (_, PlayerStatuses.Injured) => "🤕 Injured", (_, PlayerStatuses.Doubtful) => "⚠️ Doubtful️", (_, PlayerStatuses.Suspended) => "❌ Suspended", (_, PlayerStatuses.Unavailable) => "👀 Unavailable", (_, PlayerStatuses.NotInSquad) => "😐 Not in squad", (_, PlayerStatuses.Available) => "✅ Available", (_, _) => $"⁉️" });
private static void HandlePlayerUpdate(PlayerUpdate update) { if (update == null) { throw new WrongPacketTypeException(); } Player player = World.Instance.GetPlayer(update.UserID); if (player == null) { Debug.LogError("No player exists for PlayerUpdate received!"); return; } if (!player.Active) { return; } player.Move(update.MoveX, update.MoveY); player.Facing = update.Facing; if (update.PickUp) { player.PickUp(); } }
public static void Main(string[] args) { //MapData.MapList(); //this has to be packed once all mapdata is gotten. ObjectData.load(); ItemData.load(); //this has to be first because npcDrops use itemData.. i think. NpcData.load(); //first load the npc data. NpcDrop.load(); //second load the npc drops. [order does matter here, as it binds to npcData]. NpcSpawn.load(); //finally you can spawn the npcs. LaddersAndStairs.load(); objectManager = new WorldObjectManager(); groundItemManager = new GroundItemManager(); shopManager = new ShopManager(); minigames = new MinigamesHandler(); grandExchange = new GrandExchange(); clanManager = new ClanManager(); packetHandlers = new PacketHandlers(); loginHandler = new LoginHandler(); registerEvent(new RunEnergyEvent()); registerEvent(new LevelChangeEvent()); registerEvent(new SpecialRestoreEvent()); registerEvent(new SkullCycleEvent()); registerEvent(new AreaVariables()); registerEvent(new AggressiveNpcEvent()); registerEvent(new LowerPotionCyclesEvent()); objectManager.getFarmingPatches().processPatches(); isRunning = true; new Thread(new ThreadStart(Server.eventProcessingThread)).Start(); Console.Title = "RS2 530 C# Server"; // setup the listener try { IPEndPoint ipe = new IPEndPoint(0, Constants.SERVER_PORT); serverListenerSocket = new System.Net.Sockets.Socket(ipe.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); serverListenerSocket.Bind(ipe); serverListenerSocket.Listen(25); //backlog serverListenerSocket.BeginAccept(new AsyncCallback(acceptCallback), serverListenerSocket); Console.WriteLine("RS2 530 C# server started on port " + Constants.SERVER_PORT); } catch (SocketException ioe) { Misc.WriteError("Error: Unable to startup listener on " + Constants.SERVER_PORT + " - port already in use?"); Misc.WriteError(ioe.Message.ToString()); isRunning = false; } while (isRunning) { // could do game updating stuff in here... // maybe do all the major stuff here in a big loop and just do the packet // sending/receiving in the client subthreads. The actual packet forming code // will reside within here and all created packets are then relayed by the subthreads. // This way we avoid all the sync'in issues // The rough outline could look like: // doPlayers() // updates all player related stuff // doNpcs() // all npc related stuff // doObjects() // doWhatever() curTime = Environment.TickCount; if (curTime - lastInfoTime >= 2000 && !toggledStats) { Console.Title = "RS2 C# Server [Players: " + players.Count + "][Connections: " + connections.Count + "]"; lastInfoTime = curTime; toggledStats = true; } else if (curTime - lastInfoTime >= 4000 && toggledStats) { Console.Title = "RS2 C# Server [Events Running: " + events.Count + "]"; lastInfoTime = curTime; toggledStats = false; } lock (connections) { foreach (Connection c in connections.ToArray()) //these are logged in players. //ThreadPool.QueueUserWorkItem(c.processQueuedPackets); { c.processQueuedPackets(null); } foreach (Connection c in connections.ToArray()) //update server. { if (LoginHandler.removableConnection(c)) { removeConnection(c); } } } lock (players) { foreach (Player p in players) { p.tick(); p.processQueuedHits(); //if (p.getWalkingQueue().hasNextStep() || p.getTeleportTo() != null) p.getWalkingQueue().getNextPlayerMovement(); } } lock (npcs) { foreach (Npc n in npcs) { n.tick(); n.processQueuedHits(); } } lock (players) { foreach (Player p in players) { if (p == null) { continue; } if (p.isActive()) { PlayerUpdate.update(p); NpcUpdate.update(p); //In case the player turns active in the loop below make sure it doesn't clear flags. if (!p.getUpdateFlags().isClearable()) { p.getUpdateFlags().setClearable(true); } } } foreach (Player p in players) { if (p.isActive() && p.getUpdateFlags().isClearable() && p.getUpdateFlags().isUpdateRequired()) { p.getUpdateFlags().clear(); } p.getHits().clear(); if (!p.getConnection().socket.Connected || p.isDisconnected()) { unregister(p); //This must be after PlayerUpdate or chance of messing up playerIndexes for PlayerUpdate } } } lock (npcs) { foreach (Npc n in npcs) { if (n.getUpdateFlags().isUpdateRequired()) { n.getUpdateFlags().clear(); } n.getHits().clear(); } } try { System.Threading.Thread.Sleep(500 - (Environment.TickCount - curTime)); } catch { } } Console.WriteLine("Server has shutdown successfully, press any key to exit console."); //Console.ReadKey(true); Console.ReadLine(); }
public void SendMyPlayerUpdate() { PlayerUpdate update = new PlayerUpdate(); update.ShipPosition = ship.Position; update.Outline = ship.Outline; update.ShipVelocity = ship.Velocity; update.State = ship.State; update.WaitCount = ship.WaitCount; update.DeathCount = ship.DeathCount; update.FlameIndex = ship.FlameIndex; update.Sounds = (int)ship.Sounds; update.Score = ship.Score; ShotUpdate shotUpdate = new ShotUpdate(); shotUpdate.ShotAge = new int[Constants.NumShots]; shotUpdate.ShotPosition = new Vector2[Constants.NumShots]; Shot[] shotArray = ship.ShotHandler.GetShotArray(); for (int i = 0; i < Constants.NumShots; i++) { shotUpdate.ShotPosition[i] = shotArray[i].Position; shotUpdate.ShotAge[i] = shotArray[i].Age; } netPeer.SendPlayerUpdate(update, shotUpdate); }
public override void UpdateFromServer(PlayerSync sync) { Spawn(); // Sync team name TeamManager.Instance.SyncTeam(sync.Team); SetSkin(sync.Skin); Score = sync.Score; Carry(sync.Carrying); // Apply sync if (sync.WasHit) { Hit(); } Health = sync.Health; transform.position = new Vector2(sync.PosX, sync.PosY); // Find earliest input after sync int earliestInputIndex = 0; bool found = false; for (int i = 0; i < InputBufferSize; i++) { PlayerUpdate input = _inputBuffer[i]; if (input == null) { continue; } // Remove inputs older than sync if (sync.Time > input.Time) { _inputBuffer[i] = null; continue; } if (found && input.Time > _inputBuffer[earliestInputIndex].Time) { continue; } earliestInputIndex = i; found = true; } if (found) { // Debug.Log("Latency: " + (_inputBuffer[earliestInputIndex].Time - sync.Time).Milliseconds + "ms"); // Apply inputs int inputsBehind = 0; for (InputBufferIndex = earliestInputIndex; _inputBuffer[InputBufferIndex] != null; InputBufferIndex++) { inputsBehind++; PlayerUpdate input = _inputBuffer[InputBufferIndex]; Move(new Vector2(input.MoveX, input.MoveY)); // Prevent infinite loops if (inputsBehind >= InputBufferSize) { break; } } } }
public void SendMyPlayerUpdate() { if (!networkEnabled) return; PlayerUpdate update = new PlayerUpdate(); update.WorldMatrix = playerShip.Position.WorldMatrix; update.State = (int)playerShip.State; update.WaitCount = playerShip.WaitCount; update.DeathCount = playerShip.DeathCount; update.Sounds = (int)playerShip.Sounds; update.Score = playerShip.Score; ShotUpdate shotUpdate = new ShotUpdate(); shotUpdate.ShotAge = new float[Constants.NumShots]; shotUpdate.ShotPosition = new Vector3[Constants.NumShots]; shotUpdate.ShotAlive = new bool[Constants.NumShots]; Photon[] shotArray = playerShip.ShotHandler.GetShotArray(); for (int i = 0; i < Constants.NumShots; i++) { shotUpdate.ShotPosition[i] = shotArray[i].Location; shotUpdate.ShotAge[i] = shotArray[i].Age; shotUpdate.ShotAlive[i] = shotArray[i].Alive; } peer.SendPlayerUpdate(update, shotUpdate); }
public void DataReceived(object sender, ReceiveEventArgs rea) { int senderID = rea.Message.SenderID; //Ignore messages received before we are initialized if ((gameState == GameStates.Loading) || (gameState == GameStates.Config)) { rea.Message.ReceiveData.Dispose(); return; } byte mType = (byte)rea.Message.ReceiveData.Read(typeof(byte)); MessageType messageType = (MessageType)mType; switch (messageType) { case MessageType.PlayerUpdateID: { PlayerUpdate update = (PlayerUpdate)rea. Message.ReceiveData.Read(typeof(PlayerUpdate)); ShotUpdate shotUpdate = new ShotUpdate(); shotUpdate.ShotPosition = new Vector2[Constants.NumShots]; shotUpdate.ShotAge = new int[Constants.NumShots]; for (int i = 0; i < Constants.NumShots; i++) { shotUpdate.ShotPosition[i] = (Vector2)rea.Message.ReceiveData.Read(typeof(Vector2)); shotUpdate.ShotAge[i] = (int)rea.Message.ReceiveData.Read(typeof(int)); } rea.Message.ReceiveData.Dispose(); lock (otherPlayers) { object playerObject = otherPlayers[senderID]; if (null == playerObject) { return; } RemotePlayer player = (RemotePlayer)playerObject; Shot[] shotArray = new Shot[Constants.NumShots]; for (int i = 0; i < Constants.NumShots; i++) { shotArray[i] = new Shot(); shotArray[i].Position = shotUpdate.ShotPosition[i]; shotArray[i].Age = shotUpdate.ShotAge[i]; } player.Ship.ShotHandler.SetShotArray(shotArray); player.Ship.Position = update.ShipPosition; player.Ship.Outline = update.Outline; player.Ship.Velocity = update.ShipVelocity; player.Ship.State = update.State; player.Ship.WaitCount = update.WaitCount; player.Ship.DeathCount = update.DeathCount; player.Ship.FlameIndex = update.FlameIndex; player.Ship.Sounds = (Sounds)update.Sounds; player.Ship.Score = update.Score; player.UpdateTime = DateTime.Now; player.Active = true; otherPlayers[senderID] = player; } break; } case MessageType.GameParamUpdateID: { GameParamUpdate update = (GameParamUpdate)rea.Message. ReceiveData.Read(typeof(GameParamUpdate)); rea.Message.ReceiveData.Dispose(); gravity = update.Gravity; gameSpeed = update.GameSpeed; if (update.BounceBack != 0) { bounceBack = true; } else { bounceBack = false; } if (update.InverseGravity != 0) { inverseGravity = true; } else { inverseGravity = false; } if (update.BlackHole != 0) { blackHole = true; } else { blackHole = false; } Size newWindowSize = update.WindowSize; Rectangle newBounds = new Rectangle(this.windowBounds.Location, newWindowSize); //Initialize(newBounds); break; } case MessageType.Add1ToScore: { rea.Message.ReceiveData.Dispose(); ship.Score += 1; break; } case MessageType.Add2ToScore: { rea.Message.ReceiveData.Dispose(); ship.Score += 2; break; } case MessageType.GamePaused: { rea.Message.ReceiveData.Dispose(); gameState = GameStates.Paused; break; } case MessageType.GameRunning: { rea.Message.ReceiveData.Dispose(); if (gameState == GameStates.Paused) { gameState = GameStates.Running; } break; } } }
public void DataReceived(object sender, ReceiveEventArgs rea) { int senderID = rea.Message.SenderID; //Ignore messages received before we are initialized if ((gameState == GameStates.Loading) || (gameState == GameStates.Config)) { rea.Message.ReceiveData.Dispose(); return; } byte mType = (byte)rea.Message.ReceiveData.Read(typeof(byte)); MessageType messageType = (MessageType)mType; switch (messageType) { case MessageType.PlayerUpdateID: { PlayerUpdate update = (PlayerUpdate)rea.Message.ReceiveData.Read(typeof(PlayerUpdate)); ShotUpdate shotUpdate = new ShotUpdate(); shotUpdate.ShotPosition = new Vector3[Constants.NumShots]; shotUpdate.ShotAge = new float[Constants.NumShots]; shotUpdate.ShotAlive = new bool[Constants.NumShots]; for (int i = 0; i < Constants.NumShots; i++) { shotUpdate.ShotPosition[i] = (Vector3)rea.Message.ReceiveData.Read(typeof(Vector3)); shotUpdate.ShotAge[i] = (int)rea.Message.ReceiveData.Read(typeof(int)); shotUpdate.ShotAlive[i] = (bool)rea.Message.ReceiveData.Read(typeof(bool)); } rea.Message.ReceiveData.Dispose(); lock (opponentShip) { opponentShip.Position.WorldMatrix = update.WorldMatrix; opponentShip.Score = update.Score; opponentShip.Sounds = (Sounds)update.Sounds; opponentShip.WaitCount = update.WaitCount; opponentShip.SetState((ShipState)update.State); Photon[] shotArray = opponentShip.ShotHandler.GetShotArray(); for (int i = 0; i < Constants.NumShots; i++) { shotArray[i].Location = shotUpdate.ShotPosition[i]; shotArray[i].Age = shotUpdate.ShotAge[i]; shotArray[i].Alive = shotUpdate.ShotAlive[i]; } opponentShip.ShotHandler.SetShotArray(shotArray); } break; } case MessageType.Add1ToScore: { rea.Message.ReceiveData.Dispose(); playerShip.Score += 1; break; } case MessageType.GamePaused: { rea.Message.ReceiveData.Dispose(); gameState = GameStates.Paused; break; } case MessageType.GameRunning: { rea.Message.ReceiveData.Dispose(); if (gameState == GameStates.Paused) { gameState = GameStates.Running; } break; } } }
public void RegisterForPlayerUpdates(PlayerUpdate p) { PacketProcessors.PlayerUpdateEvent += p; }
internal void EmitPlayerUpdate(PlayerUpdatePacket packet) { Position = packet.State.Position; PlayerUpdate?.Invoke(this, packet); }
public void UpdateArmlet(PlayerUpdate playerStatusUpdate) { var armlet = _armlets[playerStatusUpdate.ArmletID]; armlet.Update(playerStatusUpdate); }
public void PacketReceived(NetIncomingMessage msg) { if (msg == null) { if (_currentScene == _gameSceneName && _loaded) { PropertyInfo property = typeof(StandardLevelGameplayManager).GetProperty("gameState"); property.DeclaringType.GetProperty("gameState"); property.GetSetMethod(true).Invoke(_gameManager, new object[] { StandardLevelGameplayManager.GameState.Failed }); } return; } msg.Position = 0; switch ((CommandType)msg.ReadByte()) { case CommandType.UpdatePlayerInfo: { msg.Position += 64; bool fullUpdate = (msg.ReadByte() == 1); int playersCount = msg.ReadInt32(); if (_playerIds == null) { _playerIds = new List <ulong>(playersCount); } else if (_playerIds.Count > playersCount) { _playerIds.Clear(); } if (playerScores == null) { playerScores = new List <PlayerScore>(playersCount); } else if (playerScores.Count > playersCount) { playerScores.Clear(); } _spectatorInRoom = false; for (int i = 0; i < playersCount; i++) { ulong playerId = msg.ReadUInt64(); if (_playerIds.Count > i) { _playerIds[i] = playerId; } else { _playerIds.Add(playerId); } if (players.TryGetValue(playerId, out OnlinePlayerController player)) { if (player == null) { player = new GameObject("OnlinePlayerController").AddComponent <OnlinePlayerController>(); players[playerId] = player; } if (fullUpdate) { PlayerInfo playerInfo = new PlayerInfo(msg); player.playerInfo = playerInfo; _spectatorInRoom |= playerInfo.updateInfo.playerState == PlayerState.Spectating; } else { PlayerUpdate update = new PlayerUpdate(msg); player.NewUpdateReceived(update); byte hitCount = msg.ReadByte(); if (player.playerInfo.hitsLastUpdate.Count > 0) { player.playerInfo.hitsLastUpdate.Clear(); } for (int j = 0; j < hitCount; j++) { player.playerInfo.hitsLastUpdate.Add(new HitData(msg)); } _spectatorInRoom |= update.playerState == PlayerState.Spectating; } } else { if (fullUpdate) { player = new GameObject("OnlinePlayerController").AddComponent <OnlinePlayerController>(); PlayerInfo playerInfo = new PlayerInfo(msg); player.playerInfo = playerInfo; _spectatorInRoom |= playerInfo.updateInfo.playerState == PlayerState.Spectating; players.Add(playerId, player); } else { Plugin.log.Error("Not enough info to create new player controller! Waiting for full update..."); sendFullUpdate = true; new PlayerUpdate(msg); byte hitCount = msg.ReadByte(); msg.ReadBytes(hitCount * 5); } } if (player != null) { player.SetAvatarState(!Client.Instance.inRadioMode && IsPlayerVisible(player.playerInfo.playerId)); player.SetBlocksState(!Client.Instance.inRadioMode && _currentScene == _gameSceneName && Config.Instance.ShowOtherPlayersBlocks && !Client.Instance.playerInfo.Equals(player.playerInfo) && !Config.Instance.SpectatorMode && player.playerInfo.updateInfo.playerState == PlayerState.Game); } } _playerIds.Sort(); int localPlayerIndex = _playerIds.IndexOf(Client.Instance.playerInfo.playerId); bool needToRemovePlayer = false; for (int i = 0; i < playerScores.Count; i++) { playerScores[i] = default; } foreach (var pair in players) { if (!_playerIds.Contains(pair.Key)) { needToRemovePlayer = true; } else { int playerIndex = _playerIds.IndexOf(pair.Key); pair.Value.avatarOffset = (playerIndex - localPlayerIndex) * (_currentScene == _gameSceneName ? 5f : 0f); while (playerScores.Count <= playerIndex) { playerScores.Add(default); } playerScores[playerIndex] = new PlayerScore(pair.Value); }
private void PacketReceived(NetIncomingMessage msg) { if (Config.Instance.SpectatorMode && !Client.Instance.inRadioMode && _currentScene == "GameCore") { msg.Position = 0; CommandType commandType = (CommandType)msg.ReadByte(); if (commandType == CommandType.GetPlayerUpdates) { int playersCount = msg.ReadInt32(); for (int j = 0; j < playersCount; j++) { try { ulong playerId = msg.ReadUInt64(); byte packetsCount = msg.ReadByte(); ReplayData replay; if (playerUpdates.TryGetValue(playerId, out replay)) { if (replay.playerInfo == null) { if (InGameOnlineController.Instance.players.TryGetValue(playerId, out OnlinePlayerController playerController)) { replay.playerInfo = playerController.playerInfo; } } for (int k = 0; k < packetsCount; k++) { PlayerUpdate player = new PlayerUpdate(msg); replay.updates.Add(player); } byte hitCount = msg.ReadByte(); for (int i = 0; i < hitCount; i++) { HitData hit = new HitData(msg); if (!replay.hits.ContainsKey(hit.objectId)) { replay.hits.Add(hit.objectId, hit); } } if (replay.updates.Count > 450) { replay.updates.RemoveRange(0, replay.updates.Count - 450); } } else { replay = new ReplayData(); if (InGameOnlineController.Instance.players.TryGetValue(playerId, out OnlinePlayerController playerController)) { replay.playerInfo = playerController.playerInfo; } if (replay.playerInfo == null) { InGameOnlineController.Instance.sendFullUpdate = true; continue; } for (int k = 0; k < packetsCount; k++) { PlayerUpdate player = new PlayerUpdate(msg); replay.updates.Add(player); } byte hitCount = msg.ReadByte(); for (int i = 0; i < hitCount; i++) { HitData hit = new HitData(msg); if (!replay.hits.ContainsKey(hit.objectId)) { replay.hits.Add(hit.objectId, hit); } } playerUpdates.Add(playerId, replay); } } catch (Exception e) { #if DEBUG Plugin.log.Critical($"Unable to parse PlayerInfo! Excpetion: {e}"); #endif } } } } }
public override Packet CreatePacket() { var packet = new Packet(); WriteHeaders(packet); // Construct the byte flag representing which packets are included // in this update ushort dataPacketIdFlag = 0; // Keep track of value of current bit ushort currentTypeValue = 1; /* * foreach (var item in DataPacketIds) * { * Logger.Info(this,$"creating packet with {Enum.GetName(typeof(ServerPacketId), item)}"); * } */ for (var i = 0; i < Enum.GetNames(typeof(ServerPacketId)).Length; i++) { // Cast the current index of the loop to a ServerPacketId and check if it is // contained in the update type list, if so, we add the current bit to the flag if (DataPacketIds.Contains((ServerPacketId)i)) { dataPacketIdFlag |= currentTypeValue; } currentTypeValue *= 2; } packet.Write(dataPacketIdFlag); // TODO: this is a mess, we have an interface that exposes a write and read method // to packets, but we don't really use the abstraction since we still need to // write and read in a specific order to ensure consistency // The same holds then for determining whether this packet contains reliable data // and finding a way to elegantly copy reliable data to a new packet if (DataPacketIds.Contains(ServerPacketId.HelloServer)) { HelloServer.WriteData(packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerUpdate)) { PlayerUpdate.WriteData(packet); } if (DataPacketIds.Contains(ServerPacketId.EntityUpdate)) { EntityUpdates.WriteData(packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerEnterScene)) { PlayerEnterScene.WriteData(packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerTeamUpdate)) { PlayerTeamUpdate.WriteData(packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerSkinUpdate)) { PlayerSkinUpdate.WriteData(packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerEmoteUpdate)) { PlayerEmoteUpdate.WriteData(packet); } // Check whether there is reliable data written in this packet // and set the boolean value accordingly _containsReliableData = DataPacketIds.Contains(ServerPacketId.HelloServer) || DataPacketIds.Contains(ServerPacketId.PlayerEnterScene) || DataPacketIds.Contains(ServerPacketId.PlayerLeaveScene) || DataPacketIds.Contains(ServerPacketId.PlayerDeath) || DataPacketIds.Contains(ServerPacketId.PlayerTeamUpdate) || DataPacketIds.Contains(ServerPacketId.PlayerSkinUpdate); packet.WriteLength(); return(packet); }
private void OnPlayerUpdate(ushort id, PlayerUpdate playerUpdate) { if (!_playerData.TryGetValue(id, out var playerData)) { Logger.Get().Warn(this, $"Received PlayerUpdate data, but player with ID {id} is not in mapping"); return; } if (playerUpdate.UpdateTypes.Contains(PlayerUpdateType.Position)) { playerData.LastPosition = playerUpdate.Position; SendDataInSameScene(id, otherId => { _netServer.GetUpdateManagerForClient(otherId).UpdatePlayerPosition(id, playerUpdate.Position); }); } if (playerUpdate.UpdateTypes.Contains(PlayerUpdateType.Scale)) { playerData.LastScale = playerUpdate.Scale; SendDataInSameScene(id, otherId => { _netServer.GetUpdateManagerForClient(otherId).UpdatePlayerScale(id, playerUpdate.Scale); }); } if (playerUpdate.UpdateTypes.Contains(PlayerUpdateType.MapPosition)) { playerData.LastMapPosition = playerUpdate.MapPosition; // If the map icons need to be broadcast, we add the data to the next packet if (_gameSettings.AlwaysShowMapIcons || _gameSettings.OnlyBroadcastMapIconWithWaywardCompass) { foreach (var idPlayerDataPair in _playerData.GetCopy()) { if (idPlayerDataPair.Key == id) { continue; } _netServer.GetUpdateManagerForClient(idPlayerDataPair.Key) .UpdatePlayerMapPosition(id, playerUpdate.MapPosition); } } } if (playerUpdate.UpdateTypes.Contains(PlayerUpdateType.Animation)) { var animationInfos = playerUpdate.AnimationInfos; // Check whether there is any animation info to be stored if (animationInfos.Count != 0) { // Set the last animation clip to be the last clip in the animation info list // Since that is the last clip that the player updated playerData.LastAnimationClip = animationInfos[animationInfos.Count - 1].ClipId; // Set the animation data for each player in the same scene SendDataInSameScene(id, otherId => { foreach (var animationInfo in animationInfos) { _netServer.GetUpdateManagerForClient(otherId).UpdatePlayerAnimation( id, animationInfo.ClipId, animationInfo.Frame, animationInfo.EffectInfo ); } }); } } }
private void Start() { rb = GetComponent <Rigidbody>(); pu = GameObject.Find("GameManager").GetComponent <PlayerUpdate>(); }
public void SetPlayerInfo(PlayerInfo _playerInfo, float offset, bool isLocal) { if (_playerInfo == default) { if (playerNameText != null) { playerNameText.gameObject.SetActive(false); } if (playerSpeakerIcon != null) { playerSpeakerIcon.gameObject.SetActive(false); } if (avatar != null && avatar.GameObject != null) { Destroy(avatar.GameObject); } return; } try { playerInfo = _playerInfo.updateInfo; playerId = _playerInfo.playerId; playerAvatarHash = _playerInfo.avatarHash; playerName = _playerInfo.playerName; if (playerNameText != null && playerSpeakerIcon != null) { if (isLocal) { playerNameText.gameObject.SetActive(false); playerSpeakerIcon.gameObject.SetActive(false); #if !DEBUG if (avatar != null) { Destroy(avatar.GameObject); } #endif } else { playerNameText.gameObject.SetActive(true); playerNameText.alignment = TextAlignmentOptions.Center; playerSpeakerIcon.gameObject.SetActive(InGameOnlineController.Instance.VoiceChatIsTalking(playerId)); } } else { return; } #if !DEBUG if ((avatar == null || currentAvatarHash != playerAvatarHash) && !isLocal) #else if ((avatar == null || currentAvatarHash != playerAvatarHash)) #endif { if (ModelSaberAPI.cachedAvatars.ContainsKey(playerAvatarHash)) { CustomAvatar.CustomAvatar cachedAvatar = ModelSaberAPI.cachedAvatars[playerAvatarHash]; if (cachedAvatar != null) { if (pendingAvatars.Contains(cachedAvatar)) { AvatarLoaded -= AvatarController_AvatarLoaded; AvatarLoaded += AvatarController_AvatarLoaded; } else if (!pendingAvatars.Contains(cachedAvatar) && !cachedAvatar.IsLoaded) { if (avatar != null) { Destroy(avatar.GameObject); } avatar = AvatarSpawner.SpawnAvatar(defaultAvatarInstance, this); exclusionScript = avatar.GameObject.GetComponentsInChildren <AvatarScriptPack.FirstPersonExclusion>().FirstOrDefault(); if (exclusionScript != null) { exclusionScript.SetVisible(); } pendingAvatars.Add(cachedAvatar); AvatarLoaded -= AvatarController_AvatarLoaded; AvatarLoaded += AvatarController_AvatarLoaded; cachedAvatar.Load((CustomAvatar.CustomAvatar loadedAvatar, AvatarLoadResult result) => { if (result == AvatarLoadResult.Completed) { pendingAvatars.Remove(ModelSaberAPI.cachedAvatars[playerAvatarHash]); AvatarLoaded?.Invoke(ModelSaberAPI.cachedAvatars.First(x => x.Value == loadedAvatar).Key); } }); } else { if (avatar != null) { Destroy(avatar.GameObject); } avatar = AvatarSpawner.SpawnAvatar(cachedAvatar, this); exclusionScript = avatar.GameObject.GetComponentsInChildren <AvatarScriptPack.FirstPersonExclusion>().FirstOrDefault(); if (exclusionScript != null) { exclusionScript.SetVisible(); } currentAvatarHash = playerAvatarHash; } } } else { if (Config.Instance.DownloadAvatars) { if (ModelSaberAPI.queuedAvatars.Contains(playerAvatarHash)) { ModelSaberAPI.avatarDownloaded -= AvatarDownloaded; ModelSaberAPI.avatarDownloaded += AvatarDownloaded; } else { ModelSaberAPI.avatarDownloaded -= AvatarDownloaded; ModelSaberAPI.avatarDownloaded += AvatarDownloaded; SharedCoroutineStarter.instance.StartCoroutine(ModelSaberAPI.DownloadAvatarCoroutine(playerAvatarHash)); if (avatar != null) { Destroy(avatar.GameObject); } avatar = AvatarSpawner.SpawnAvatar(defaultAvatarInstance, this); exclusionScript = avatar.GameObject.GetComponentsInChildren <AvatarScriptPack.FirstPersonExclusion>().FirstOrDefault(); if (exclusionScript != null) { exclusionScript.SetVisible(); } } } } } Vector3 offsetVector = new Vector3(offset, 0f, 0f); HeadPos = playerInfo.headPos + offsetVector; RightHandPos = playerInfo.rightHandPos + offsetVector; LeftHandPos = playerInfo.leftHandPos + offsetVector; HeadRot = playerInfo.headRot; RightHandRot = playerInfo.rightHandRot; LeftHandRot = playerInfo.leftHandRot; if (playerInfo.fullBodyTracking) { RightLegPos = playerInfo.rightLegPos + offsetVector; LeftLegPos = playerInfo.leftLegPos + offsetVector; PelvisPos = playerInfo.pelvisPos + offsetVector; RightLegRot = playerInfo.rightLegRot; LeftLegRot = playerInfo.leftLegRot; PelvisRot = playerInfo.pelvisRot; } else { RightLegPos = new Vector3(); LeftLegPos = new Vector3(); PelvisPos = new Vector3(); RightLegRot = new Quaternion(); LeftLegRot = new Quaternion(); PelvisRot = new Quaternion(); } transform.position = HeadPos; playerNameText.text = playerName; if (playerInfo.playerFlags.rainbowName && !rainbowName) { playerNameText.color = playerInfo.playerNameColor; nameColor = HSBColor.FromColor(playerInfo.playerNameColor); } else if (!playerInfo.playerFlags.rainbowName && playerNameText.color != playerInfo.playerNameColor) { playerNameText.color = playerInfo.playerNameColor; } rainbowName = playerInfo.playerFlags.rainbowName; } catch (Exception e) { Plugin.log.Critical(e); } }
public void SetPlayerInfo(PlayerInfo _playerInfo, float offset, bool isLocal) { if (_playerInfo == default) { if (playerNameText != null) { playerNameText.gameObject.SetActive(false); } if (playerSpeakerIcon != null) { playerSpeakerIcon.gameObject.SetActive(false); } if (avatar != null && avatar.eventsPlayer != null) { avatar.Destroy(); avatar = null; } return; } try { playerInfo = _playerInfo.updateInfo; playerId = _playerInfo.playerId; playerAvatarHash = _playerInfo.avatarHash; playerName = _playerInfo.playerName; if (playerNameText != null && playerSpeakerIcon != null) { if (isLocal) { playerNameText.gameObject.SetActive(false); playerSpeakerIcon.gameObject.SetActive(false); #if !DEBUG if (avatar != null && avatar.eventsPlayer != null) { avatar.Destroy(); } #endif } else { playerNameText.gameObject.SetActive(true); playerNameText.alignment = TextAlignmentOptions.Center; playerSpeakerIcon.gameObject.SetActive(InGameOnlineController.Instance.VoiceChatIsTalking(playerId)); } } else { return; } #if !DEBUG if ((avatar == null || currentAvatarHash != playerAvatarHash) && !isLocal) #else if ((avatar == null || currentAvatarHash != playerAvatarHash)) #endif { if (unableToSpawnAvatar) { if (retryTimeCounter + 5f > Time.realtimeSinceStartup) { retryTimeCounter = -1f; unableToSpawnAvatar = false; } } else { if (ModelSaberAPI.cachedAvatars.ContainsKey(playerAvatarHash)) { LoadedAvatar cachedAvatar = ModelSaberAPI.cachedAvatars[playerAvatarHash]; if (cachedAvatar != null) { if (avatar != null && avatar.eventsPlayer != null) { avatar.Destroy(); avatar = null; } avatar = AvatarManager.SpawnAvatar(cachedAvatar, avatarInput); avatar.SetChildrenToLayer(10); currentAvatarHash = playerAvatarHash; } else { unableToSpawnAvatar = true; retryTimeCounter = Time.realtimeSinceStartup; } } else { if (Config.Instance.DownloadAvatars) { if (!Config.Instance.DownloadNSFWAvatars && ModelSaberAPI.nsfwAvatars.Contains(playerAvatarHash)) { unableToSpawnAvatar = true; retryTimeCounter = Time.realtimeSinceStartup; } else { ModelSaberAPI.avatarDownloaded -= AvatarDownloaded; ModelSaberAPI.avatarDownloaded += AvatarDownloaded; if (!ModelSaberAPI.queuedAvatars.Contains(playerAvatarHash)) { SharedCoroutineStarter.instance.StartCoroutine(ModelSaberAPI.DownloadAvatarCoroutine(playerAvatarHash)); if (avatar != null && avatar.eventsPlayer != null) { avatar.Destroy(); } avatar = AvatarManager.SpawnAvatar(defaultAvatarInstance, avatarInput); avatar.SetChildrenToLayer(10); } } } } } } Vector3 offsetVector = new Vector3(offset, 0f, 0f); avatarInput.headPos = playerInfo.headPos + offsetVector; avatarInput.rightHandPos = playerInfo.rightHandPos + offsetVector; avatarInput.leftHandPos = playerInfo.leftHandPos + offsetVector; avatarInput.headRot = playerInfo.headRot; avatarInput.rightHandRot = playerInfo.rightHandRot; avatarInput.leftHandRot = playerInfo.leftHandRot; avatarInput.poseValid = true; avatarInput.fullBodyTracking = playerInfo.fullBodyTracking; if (playerInfo.fullBodyTracking) { avatarInput.rightLegPos = playerInfo.rightLegPos + offsetVector; avatarInput.leftLegPos = playerInfo.leftLegPos + offsetVector; avatarInput.pelvisPos = playerInfo.pelvisPos + offsetVector; avatarInput.rightLegRot = playerInfo.rightLegRot; avatarInput.leftLegRot = playerInfo.leftLegRot; avatarInput.pelvisRot = playerInfo.pelvisRot; } transform.position = avatarInput.headPos; playerNameText.text = playerName; if (playerInfo.playerFlags.rainbowName && !rainbowName) { playerNameText.color = playerInfo.playerNameColor; nameColor = HSBColor.FromColor(playerInfo.playerNameColor); } else if (!playerInfo.playerFlags.rainbowName && playerNameText.color != playerInfo.playerNameColor) { playerNameText.color = playerInfo.playerNameColor; } rainbowName = playerInfo.playerFlags.rainbowName; } catch (Exception e) { Plugin.log.Critical(e); } }
public override void ReadPacket() { ReadHeaders(Packet); // Read the byte flag representing which packets // are included in this update var dataPacketIdFlag = Packet.ReadUShort(); // Keep track of value of current bit var currentTypeValue = 1; for (var i = 0; i < Enum.GetNames(typeof(ServerPacketId)).Length; i++) { // If this bit was set in our flag, we add the type to the list if ((dataPacketIdFlag & currentTypeValue) != 0) { DataPacketIds.Add((ServerPacketId)i); } // Increase the value of current bit currentTypeValue *= 2; } /* * foreach (var item in DataPacketIds) * { * Logger.Info(this,$"reading packet with {Enum.GetName(typeof(ServerPacketId), item)}"); * } */ if (DataPacketIds.Contains(ServerPacketId.HelloServer)) { HelloServer.ReadData(Packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerUpdate)) { PlayerUpdate.ReadData(Packet); } if (DataPacketIds.Contains(ServerPacketId.EntityUpdate)) { EntityUpdates.ReadData(Packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerEnterScene)) { PlayerEnterScene.ReadData(Packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerTeamUpdate)) { PlayerTeamUpdate.ReadData(Packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerSkinUpdate)) { PlayerSkinUpdate.ReadData(Packet); } if (DataPacketIds.Contains(ServerPacketId.PlayerEmoteUpdate)) { PlayerEmoteUpdate.ReadData(Packet); } }
/// <summary> /// Encodes the packet. /// </summary> /// <param name="context"></param> public override void Encode(PlayerUpdateContext context) { builder.PutBytes(PlayerUpdate.Update(context.GetPlayer()).GetBuffer()); }
public void UpdateArmlet(PlayerUpdate playerStatusUpdate) { var armlet = Get(playerStatusUpdate.ArmletID); armlet.Update(playerStatusUpdate); }
public static bool IsRotNaN(this PlayerUpdate _info) { return(float.IsNaN(_info.headRot.x) || float.IsNaN(_info.headRot.y) || float.IsNaN(_info.headRot.z) || float.IsNaN(_info.headRot.w) || float.IsNaN(_info.leftHandRot.x) || float.IsNaN(_info.leftHandRot.y) || float.IsNaN(_info.leftHandRot.z) || float.IsNaN(_info.leftHandRot.w) || float.IsNaN(_info.rightHandRot.x) || float.IsNaN(_info.rightHandRot.y) || float.IsNaN(_info.rightHandRot.z) || float.IsNaN(_info.rightHandRot.w)); }