public static void PlayerShoot(object caller, DataStreamReader stream, ref DataStreamReader.Context context, NetworkConnection source) { MyClientBehaviour client = caller as MyClientBehaviour; //playerId and bullet id uint playerId = stream.ReadUInt(ref context); uint networkId = stream.ReadUInt(ref context); //position float posX = stream.ReadFloat(ref context); float posY = stream.ReadFloat(ref context); float posZ = stream.ReadFloat(ref context); //rotation float rotX = stream.ReadFloat(ref context); float rotY = stream.ReadFloat(ref context); float rotZ = stream.ReadFloat(ref context); //spawn a bullet with the received networkId and position/direction GameObject bullet; uint id = NetworkId.Spawn(Resources.Load("ClientBullet"), ref client.repository, networkId); if (NetworkId.Find(id, out bullet, ref client.repository)) { //set playerId on bullet script, set position and direction of player that's shooting bullet.transform.rotation = Quaternion.Euler(rotX, rotY, rotZ); bullet.transform.position = new Vector3(posX, posY, posZ); } }
public static void DestroyNetworkedObject(object caller, DataStreamReader stream, ref DataStreamReader.Context context, NetworkConnection source) { MyClientBehaviour client = caller as MyClientBehaviour; uint networkId = stream.ReadUInt(ref context); NetworkId.DestroyNetworked(networkId, ref client.repository); }
public void Read(UdpPacket packet) { ID = (WeaponID)packet.ReadInt(); currentAmmo = packet.ReadInt(); totalAmmo = packet.ReadInt(); networkId = new NetworkId(packet.ReadULong()); }
private async Task ImportPokemonSet(object arg) { using (var client = new WebClient()) { var json = await client.DownloadStringTaskAsync($"https://api.pokemontcg.io/v1/cards?setCode={SelectedSet.SetCode}&supertype=Pok%C3%A9mon").ConfigureAwait(false); var headers = client.ResponseHeaders; int cardsFound = int.Parse(headers.Get("Count")); int pageSize = int.Parse(headers.Get("Page-Size")); if (cardsFound > pageSize) { //TODO MessageBox.Show("There are more cards!!!"); } var pokemons = new List <PokemonViewModel>(); foreach (var card in JsonConvert.DeserializeObject <JsonPokemonList>(json).Cards) { var pokemon = PokemonCreator.CreateCardFromSdkCard(card); var model = new PokemonViewModel(pokemon); model.Card.CardId = NetworkId.Generate(); pokemons.Add(model); } foreach (var pokemon in pokemons.OrderBy(x => x.Card.Name)) { PokemonCards.Add(pokemon); } SelectedCard = PokemonCards.First(); } }
private void ImportPokemon(object obj) { var dialog = new ImportPokemon(); if (dialog.ShowDialog().Value) { using (var client = new WebClient()) { try { var json = client.DownloadString(dialog.Url); var pokemonSdk = JsonConvert.DeserializeObject <JsonPokemon>(json); var pokemon = PokemonCreator.CreateCardFromSdkCard(pokemonSdk); PokemonCards.Add(new PokemonViewModel(pokemon)); SelectedCard = PokemonCards.Last(); SelectedCard.Card.CardId = NetworkId.Generate(); } catch { } } } }
/// <summary> /// Marks replicable as successfully created, ready to receive events and state groups data. /// </summary> void SetReplicableReady(NetworkId networkId, IMyReplicable replicable) { MyPendingReplicable pendingReplicable; if (m_pendingReplicables.TryGetValue(networkId, out pendingReplicable)) { var ids = pendingReplicable.StateGroupIds; AddNetworkObjectClient(networkId, replicable); using (m_tmpGroups) { replicable.GetStateGroups(m_tmpGroups); Debug.Assert(ids.Count == m_tmpGroups.Count, "Number of state groups on client and server for replicable does not match"); for (int i = 0; i < m_tmpGroups.Count; i++) { if (m_tmpGroups[i] != replicable) AddNetworkObjectClient(ids[i], m_tmpGroups[i]); } } m_pendingReplicables.Remove(networkId); m_eventBuffer.ProcessEvents(networkId, m_eventHandler); m_sendStream.ResetWrite(); m_sendStream.WriteNetworkId(networkId); m_callback.SendReplicableReady(m_sendStream); } else { // Replicable was already destroyed on server, during it's load on client m_eventBuffer.RemoveEvents(networkId); replicable.OnDestroy(); } }
public GameField PlayCard(NetworkId gameId, NetworkId cardId) { GameField game; if (!ActiveGames.TryGetValue(gameId, out game)) { return(null); } if (game.GameState == GameFieldState.GameOver) { return(game); } var card = game.Cards[cardId]; if (card is TrainerCard) { game.PlayTrainerCard((TrainerCard)card); } else if (card is PokemonCard) { game.PlayPokemon((PokemonCard)card); } return(game); }
public void TriggerEvent(NetworkId attackingPlayer) { var attackingPokemon = GameController.Instance.Player.Id.Equals(attackingPlayer) ? GameController.Instance.Player.ActivePokemonCard : GameController.Instance.OpponentPlayer.ActivePokemonCard; var defending = GameController.Instance.Player.Id.Equals(attackingPlayer) ? GameController.Instance.OpponentPlayer.ActivePokemonCard : GameController.Instance.Player.ActivePokemonCard; var cardRenderer = GameController.Instance.GetCardRendererById(attackingPokemon.Id); var startPos = cardRenderer.GetComponent <RectTransform>().position; var targetPos = GameController.Instance.GetCardRendererById(defending.Id).GetComponent <RectTransform>().position; var canvas = cardRenderer.GetComponent <Canvas>(); canvas.sortingOrder += 1; cardRenderer.gameObject.LeanMove(targetPos, 0.5f).setEaseInCubic().setOnComplete(() => { cardRenderer.gameObject.LeanMove(startPos, 0.4f).setEaseInOutCubic().setOnComplete(() => { canvas.sortingOrder -= 1; }); GameEventHandler.Instance.EventCompleted(); }); }
private async Task ImportEnergyCardsFromSet(object arg) { using (var client = new WebClient()) { var json = await client.DownloadStringTaskAsync($"https://api.pokemontcg.io/v1/cards?setCode={SelectedSet.SetCode}&supertype=Energy").ConfigureAwait(false); var headers = client.ResponseHeaders; int cardsFound = int.Parse(headers.Get("Count")); int pageSize = int.Parse(headers.Get("Page-Size")); if (cardsFound > pageSize) { //TODO } foreach (var card in JsonConvert.DeserializeObject <PokemonTcgSdk.Energy>(json).Cards) { EnergyCards.Add(new EnergyCard() { Name = card.Name, ImageUrl = card.ImageUrlHiRes, SetCode = card.SetCode, IsBasic = card.SubType.ToLower() == "basic", Amount = 1, EnergyType = EnergyTypes.Colorless, CardId = NetworkId.Generate() }); } SelectedEnergyCard = EnergyCards.Last(); } }
private void OnStartEnterAmount(object message, NetworkId messageId) { SpecialState = SpecialGameState.EnteringAmount; EnterAmountPanel.gameObject.SetActive(true); EnterAmountPanel.Init((AskForAmountMessage)message); EnableButtons(); }
private void OnStartSelectingOpponentPokemon(object message, NetworkId messageId) { selectedCards.Clear(); var selectOpponentMessage = ((SelectOpponentPokemonMessage)message); var maxCount = selectOpponentMessage.MaxCount; var minCount = selectOpponentMessage.MinCount; minSelectedCardCount = minCount; maxSelectedCardCount = maxCount; if (selectOpponentMessage.Filter != null) { currentDeckFilters.Add(selectOpponentMessage.Filter); } SpecialState = SpecialGameState.SelectingOpponentsPokemon; EnableButtons(); if (!string.IsNullOrEmpty(selectOpponentMessage.Info)) { infoText.text = selectOpponentMessage.Info; } else { var countString = maxCount == minCount?maxCount.ToString() : "up to " + maxCount; infoText.text = $"Select {countString} of your opponents Pokémon"; } }
private void OnStartDiscardCards(object message, NetworkId messageId) { var discardMessage = ((DiscardCardsMessage)message); selectedCards.Clear(); SpecialState = SpecialGameState.DiscardingCards; minSelectedCardCount = discardMessage.MinCount; maxSelectedCardCount = discardMessage.Count; currentDeckFilters.AddRange(discardMessage.Filters); EnableButtons(); if (minSelectedCardCount > 1) { doneButton.SetActive(true); } if (!string.IsNullOrEmpty(discardMessage.Info)) { infoText.text = discardMessage.Info; } else if (minSelectedCardCount != maxSelectedCardCount) { string cardsText = maxSelectedCardCount > 1 ? "cards" : "card"; infoText.text = $"Discard up to {maxSelectedCardCount} {cardsText} from your hand"; } else { string cardsText = minSelectedCardCount > 1 ? "cards" : "card"; infoText.text = $"Discard {minSelectedCardCount} {cardsText} from your hand"; } }
private void OnYesNoMessage(object message, NetworkId messageId) { infoText.text = ((YesNoMessage)message).Message; SpecialState = SpecialGameState.SelectingYesNo; YesButton.SetActive(true); NoButton.SetActive(true); }
private void OnBeginSelectYourPokemon(object message, NetworkId messageId) { var selectMessage = (SelectFromYourPokemonMessage)message; SpecialState = SpecialGameState.SelectPokemonMatchingFilter; EnableButtons(); minSelectedCardCount = 1; maxSelectedCardCount = 1; if (!string.IsNullOrWhiteSpace(selectMessage.Info)) { infoText.text = selectMessage.Info; currentDeckFilters.Add(new PokemonOwnerAndTypeFilter(myId)); } else if (selectMessage.TargetTypes.Any()) { var typeText = string.Join(" ", selectMessage.TargetTypes.Select(type => Enum.GetName(typeof(EnergyTypes), type))); infoText.text = $"Select one of your {typeText} Pokémon"; currentDeckFilters.Add(new PokemonOwnerAndTypeFilter(myId, selectMessage.TargetTypes[0])); } else { infoText.text = "Select one of your Pokémon"; currentDeckFilters.Add(new PokemonOwnerAndTypeFilter(myId)); } if (selectMessage.Filter != null) { currentDeckFilters.Add(selectMessage.Filter); } }
public MyStateDataEntry(IMyReplicable owner, NetworkId groupId, IMyStateGroup group) { Priority = 0; Owner = owner; GroupId = groupId; Group = group; }
public bool Addnewssingleimages() { DataTable objDT = new DataTable(); SqlConnection _newconn = new SqlConnection(GetnetworkID(NetworkId.ToString())); int cnt = 0; try { SqlCommand _spcommand = new SqlCommand("AK_SP_AddSinglegettyimage", _newconn); _spcommand.CommandType = CommandType.StoredProcedure; _spcommand.Parameters.Add("@RandomId", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(RandomId) ? RandomId : " "; _spcommand.Parameters.Add("@SelectnewsImage", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imagename) ? imagename : " "; _spcommand.Parameters.Add("@sitId", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(SiteID) ? SiteID : " "; _spcommand.Parameters.Add("@Gettyurl", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imageurl) ? imageurl : " "; _spcommand.Parameters.Add("@ImageDesc", SqlDbType.NVarChar).Value = !string.IsNullOrEmpty(imagetxtbelow) ? imagetxtbelow : " "; _newconn.Open(); _spcommand.ExecuteNonQuery(); _newconn.Close(); } catch (Exception ex) { if (_newconn.State == ConnectionState.Open) { _newconn.Close(); } CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Client, "Gettyimages-addimages-Addnewsimages-", ex); } return(true); }
/// <summary> /// Initializes a new instance of the <see cref="ServerNetworkArgument"/> class /// with the specified network ID. /// </summary> /// <param name="networkId">The network ID.</param> /// <exception cref="ArgumentNullException">If <paramref name="networkId"/> is <see langword="null"/>.</exception> public ServerNetworkArgument(NetworkId networkId) { if (networkId == null) throw new ArgumentNullException("networkId"); _uuid = networkId; }
private void OnBeginSelectStatus(object message, NetworkId arg2) { SpecialState = SpecialGameState.SelectingStatus; EnableButtons(); SelectStatusPanel.gameObject.SetActive(true); SelectStatusPanel.Init((PickStatusMessage)message); }
/// <summary> /// Enqueues event that have to be done on target object. /// </summary> /// <param name="stream">Stream with event data.</param> /// <param name="targetObjectId">Object id that is a target of the event.</param> /// <param name="blockingObjectId">Object id that is blocking target to be processed. 'NetworkId.Invalid' if none.</param> /// <param name="eventId">Event id.</param> /// <param name="sender">Endpoint.</param> public void EnqueueEvent(BitStream stream, NetworkId targetObjectId, NetworkId blockingObjectId, uint eventId, EndpointId sender) { int requiredByteSize = stream.ByteLength - stream.BytePosition + 1; var e = ObtainEvent(); e.Stream.ResetWrite(); e.Stream.WriteBitStream(stream); e.Stream.ResetRead(); e.TargetObjectId = targetObjectId; e.BlockingObjectId = blockingObjectId; e.EventId = eventId; e.Sender = sender; e.IsBarrier = false; MyObjectEventsBuffer eventBuffer; if (!m_buffer.TryGetValue(targetObjectId, out eventBuffer)) { eventBuffer = new MyObjectEventsBuffer(); eventBuffer.Events = ObtainList(); m_buffer.Add(targetObjectId, eventBuffer); } eventBuffer.IsProcessing = false; eventBuffer.Events.Enqueue(e); }
public override NetworkMessage ToNetworkMessage(NetworkId senderId) { return(new NetworkMessage(MessageType, this, senderId, NetworkId.Generate()) { RequiresResponse = false }); }
/// <summary> /// Process blocking event. /// </summary> /// <param name="targetObjectId">Target object id for which to process.</param> /// <param name="eventToProcess">Event to be processed.</param> /// <param name="caller">Parent Network id from which this is called. Set NetworkId.Invalid if no parent.</param> /// <param name="eventHandler">Handler for processing event.</param> /// <param name="isBlockedHandler">Handler for checking if processing of events should be canceled.</param> /// <param name="postProcessQueue">Queue that should be post processed.</param> /// <returns>True if was success.</returns> private bool ProcessBlockingEvent(NetworkId targetObjectId, MyBufferedEvent eventToProcess, NetworkId caller, Handler eventHandler, IsBlockedHandler isBlockedHandler, ref Queue <NetworkId> postProcessQueue) { if (isBlockedHandler(eventToProcess.TargetObjectId, eventToProcess.BlockingObjectId)) { return(false); } bool result = this.TryLiftBarrier(eventToProcess.BlockingObjectId); // If success than we can proceede with blocking event. // If not, that means barrier holder have some events before actual barrier. Then we need to process that first. if (result) { eventHandler(eventToProcess.Stream, eventToProcess.TargetObjectId, eventToProcess.BlockingObjectId, eventToProcess.EventId, eventToProcess.Sender); if (eventToProcess.BlockingObjectId.IsValid && !eventToProcess.BlockingObjectId.Equals(caller)) { postProcessQueue.Enqueue(eventToProcess.BlockingObjectId); } } else { bool success = ProcessEvents(eventToProcess.BlockingObjectId, eventHandler, isBlockedHandler, targetObjectId); return(success); } return(true); }
public void SelectPrizeCard(int amount, GameField game) { if (amount <= 0) { return; } var message = new SelectPrizeCardsMessage(amount).ToNetworkMessage(NetworkId.Generate()); var response = NetworkPlayer.SendAndWaitForResponse <CardListMessage>(message); var cardsDrawn = new List <Card>(); foreach (var cardId in response.Cards) { var card = game.Cards[cardId]; PrizeCards.Remove(card); Hand.Add(card); cardsDrawn.Add(card); } game.SendEventToPlayers(new DrawCardsEvent() { Cards = new List <Card>(cardsDrawn), Player = Id }); }
public void Start(int port) { Instance = this; Clients = new ConcurrentDictionary <NetworkId, NetworkPlayer>(); Services = new Dictionary <string, IService> { { typeof(GameService).Name, new GameService() }, { typeof(ImageService).Name, new ImageService() }, { typeof(CardService).Name, new CardService() }, { typeof(PlayerService).Name, new PlayerService() }, { typeof(InfoService).Name, new InfoService() }, }; foreach (var service in Services.Values) { service.InitTypes(); } Id = NetworkId.Generate(); listener = new TcpListener(IPAddress.Parse("0.0.0.0"), port); listener.Start(); Console.WriteLine("Listening for connections..."); defaultConsoleTop = Console.CursorTop; serverThread = new Thread(Run); serverThread.Start(); }
public static void PublishTexture(NetworkId entityId, Texture2D texture, BoltConnection origin = null) { if (OnTextureChanged != null) { OnTextureChanged.Invoke(entityId, texture, origin); } }
public bool AddCategoryimages() { DataTable objDT = new DataTable(); SqlConnection _newconn = new SqlConnection(GetnetworkID(NetworkId.ToString())); int cnt = 0; try { SqlCommand _spcommand = new SqlCommand("AK_SP_AddCategoryimagesForslideshow", _newconn); _spcommand.CommandType = CommandType.StoredProcedure; _spcommand.Parameters.Add("@networkid", SqlDbType.Int).Value = NetworkId; _spcommand.Parameters.Add("@catsId", SqlDbType.Int).Value = CatID; _spcommand.Parameters.Add("@SiteID", SqlDbType.Int).Value = this.SiteID; _spcommand.Parameters.Add("@imagename", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imagename) ? imagename : " "; _spcommand.Parameters.Add("@imagetxt", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imagetxt) ? imagetxt : " "; _spcommand.Parameters.Add("@imageURL", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imageurl) ? imageurl : " "; _spcommand.Parameters.Add("@ImageBelowTxt", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imagetxtbelow) ? imagetxtbelow : " "; _spcommand.Parameters.Add("@imagecredit", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imagecredit) ? imagecredit : " "; _newconn.Open(); _spcommand.ExecuteNonQuery(); _newconn.Close(); } catch (Exception ex) { if (_newconn.State == ConnectionState.Open) { _newconn.Close(); } CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Client, "Gettyimages-addimages-Addnewsimages-", ex); } return(true); }
public DataTable GetGettyevents_toupdatecount() { DataTable objDT = new DataTable(); SqlConnection _newconn = new SqlConnection(GetnetworkID(NetworkId.ToString())); SqlDataAdapter _sdlda; DataSet _ds = new DataSet(); int cnt = 0; try { SqlCommand _spcommand = new SqlCommand("AK_SP_GettyEvents_to_updateimagecount", _newconn); _spcommand.CommandType = CommandType.StoredProcedure; _newconn.Open(); _sdlda = new SqlDataAdapter(_spcommand); _sdlda.Fill(objDT); _newconn.Close(); } catch (Exception ex) { if (_newconn.State == ConnectionState.Open) { _newconn.Close(); } CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Client, "Gettyimages-addimages-Addnewsimages-", ex); } return(objDT); }
public bool Update_GettyEvents_imagecount(int imagecount, int ID) { DataTable objDT = new DataTable(); SqlConnection _newconn = new SqlConnection(GetnetworkID(NetworkId.ToString())); try { SqlCommand _spcommand = new SqlCommand("AK_SP_UpdategettyEventsimagecount", _newconn); _spcommand.CommandType = CommandType.StoredProcedure; _spcommand.Parameters.Add("@eventId", SqlDbType.Int).Value = ID; _spcommand.Parameters.Add("@imagecount", SqlDbType.Int).Value = imagecount; _newconn.Open(); _spcommand.ExecuteNonQuery(); _newconn.Close(); } catch (Exception ex) { if (_newconn.State == ConnectionState.Open) { _newconn.Close(); } CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Client, "Gettyimages-addimages-Addnewsimages-", ex); } return(true); }
public bool AddGettyEvents() { DataTable objDT = new DataTable(); SqlConnection _newconn = new SqlConnection(GetnetworkID(NetworkId.ToString())); int cnt = 0; try { SqlCommand _spcommand = new SqlCommand("AK_SP_AddGettyEvent", _newconn); _spcommand.CommandType = CommandType.StoredProcedure; _spcommand.Parameters.Add("@eventId", SqlDbType.VarChar).Value = EventId; _spcommand.Parameters.Add("@imageurl", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(eventImageURL) ? eventImageURL : ""; _spcommand.Parameters.Add("@title", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(EventTitle) ? EventTitle : ""; _spcommand.Parameters.Add("@eventdate", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(EventDate) ? EventDate : ""; _spcommand.Parameters.Add("@imagecount", SqlDbType.VarChar).Value = ImageCount; _spcommand.Parameters.Add("@imagecaption", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imagetxtbelow) ? imagetxtbelow : ""; _newconn.Open(); _spcommand.ExecuteNonQuery(); _newconn.Close(); } catch (Exception ex) { if (_newconn.State == ConnectionState.Open) { _newconn.Close(); } CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Client, "Gettyimages-addimages-Addnewsimages-", ex); } return(true); }
public bool AddexternalimagesURL() { DataTable objDT = new DataTable(); SqlConnection _newconn = new SqlConnection(GetnetworkID(NetworkId.ToString())); int cnt = 0; try { SqlCommand _spcommand = new SqlCommand("AK_SP_Addexternalimagepostfromgetty", _newconn); _spcommand.CommandType = CommandType.StoredProcedure; _spcommand.Parameters.Add("@SiteID", SqlDbType.Int).Value = this.SiteID; _spcommand.Parameters.Add("@randomId", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(RandomId) ? RandomId : "00"; _spcommand.Parameters.Add("@exturl", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(exturl) ? exturl : " "; _spcommand.Parameters.Add("@title", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imagetxt) ? imagetxt : " "; _spcommand.Parameters.Add("@desc", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imagetxtbelow) ? imagetxtbelow : " "; _spcommand.Parameters.Add("@credit", SqlDbType.VarChar).Value = !string.IsNullOrEmpty(imagecredit) ? imagecredit : " "; _newconn.Open(); _spcommand.ExecuteNonQuery(); _newconn.Close(); } catch (Exception ex) { if (_newconn.State == ConnectionState.Open) { _newconn.Close(); } CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Client, "Gettyimages-addimages-Addnewsimages-", ex); } return(true); }
public string GetCategoryename() { string _strcatname = string.Empty; DataTable objDT = new DataTable(); SqlConnection _newconn = new SqlConnection(GetnetworkID(NetworkId.ToString())); int cnt = 0; try { SqlCommand _spcommand = new SqlCommand("AK_SP_GetCategoryename_Forgetty", _newconn); _spcommand.CommandType = CommandType.StoredProcedure; _spcommand.Parameters.Add("@SiteID", SqlDbType.Int).Value = this.SiteID; _spcommand.Parameters.Add("@catID", SqlDbType.Int).Value = this.CatID; _newconn.Open(); _strcatname = (string)_spcommand.ExecuteScalar(); _newconn.Close(); } catch (Exception ex) { if (_newconn.State == ConnectionState.Open) { _newconn.Close(); } CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Client, "Gettyimages-addimages-GetCategoryename-", ex); } return(_strcatname); }
private async Task ImportTrainerCardsFromSet(object arg) { using (var client = new WebClient()) { var json = await client.DownloadStringTaskAsync($"https://api.pokemontcg.io/v1/cards?setCode={SelectedSet.SetCode}&supertype=Trainer").ConfigureAwait(false); var headers = client.ResponseHeaders; int cardsFound = int.Parse(headers.Get("Count")); int pageSize = int.Parse(headers.Get("Page-Size")); if (cardsFound > pageSize) { //TODO } foreach (var card in JsonConvert.DeserializeObject <PokemonTcgSdk.Trainer>(json).Cards) { TrainerCards.Add(new TrainerCard { Name = card.Name, ImageUrl = card.ImageUrlHiRes, Completed = false, SetCode = card.SetCode, CardId = NetworkId.Generate() }); } SelectedTrainerCard = TrainerCards.First(); } }
public void Read(UdpPacket packet) { _entityID = packet.ReadNetworkId(); _width = packet.ReadInt(); _height = packet.ReadInt(); _format = packet.ReadInt(); }
private void OnTextureChangedFromRemote(NetworkId entityId, Texture2D texture, BoltConnection origin) { if (entity.NetworkId.Equals((entityId))) { ReplaceTexture(texture); } }
/// <summary> /// Add network object with fixed ID. /// </summary> public void AddFixedNetworkObject(uint id, IMyNetObject obj) { Debug.Assert(id != 0, "Zero is invalid id, it cannot be used."); Debug.Assert(id <= m_networkIdGenerator.ReservedCount, "Fixed id not reserved, call ReserveFixedIds"); var netId = new NetworkId(id); AddNetworkObject(netId, obj); m_fixedObjects.Add(obj); }
public MyStateDataEntry(IMyReplicable owner, NetworkId groupId, IMyStateGroup group, IMyReplicable parent) { Priority = 0; Owner = owner; GroupId = groupId; Group = group; GroupType = group.GroupType; Parent = parent; }
/// <summary> /// Broadcasts a chat message /// </summary> /// <param name="id"></param> /// <param name="message"></param> public void BroadcastChat(NetworkId id, string message) { if (!BoltNetwork.isRunning) return; var e = ChatEvent.Create(GlobalTargets.AllClients); e.Message = message; e.Sender = id; e.Send(); }
public void AddLine(NetworkId playerId, string message) { if (this._players.ContainsKey(playerId)) { ChatMessageRow chatMessageRow = UnityEngine.Object.Instantiate<ChatMessageRow>(this._messageRowPrefab); chatMessageRow._name.text = this._players[playerId]._name + " : "; chatMessageRow._name.color = this._players[playerId]._color; chatMessageRow._message.text = NGUIText.StripSymbols(message); chatMessageRow.name = this._lastMessageId++ + chatMessageRow.name; chatMessageRow.gameObject.SetActive(true); chatMessageRow.transform.parent = this._grid.transform; chatMessageRow.transform.localPosition = Vector3.zero; chatMessageRow.transform.localScale = Vector3.one; this._messageRows.Enqueue(chatMessageRow); if (this._messageRows.Count > this._historySize) { UnityEngine.Object.Destroy(this._messageRows.Dequeue().gameObject); } this._grid.repositionNow = true; this._grid.gameObject.SetActive(true); this._lastInteractionTime = Time.time; } }
public void RegisterPlayer(string name, NetworkId id) { Color color = new Color(UnityEngine.Random.Range(0.25f, 1f), UnityEngine.Random.Range(0.25f, 1f), UnityEngine.Random.Range(0.25f, 1f), 1f); color.r += 0.1f; color.g += 0.1f; color.b += 0.1f; this._players[id] = new ChatBox.Player { _name = name, _color = color }; }
public void UnregisterPlayer(NetworkId id) { this._players.Remove(id); }
protected NetworkId AddNetworkObjectServer(IMyNetObject obj) { Debug.Assert(m_isNetworkAuthority); var id = new NetworkId(m_networkIdGenerator.NextId()); AddNetworkObject(id, obj); return id; }
private bool ProcessEventsBuffer(MyObjectEventsBuffer eventsBuffer, NetworkId targetObjectId, Handler eventHandler, IsBlockedHandler isBlockedHandler, NetworkId caller, ref Queue<NetworkId> postProcessQueue) { while (eventsBuffer.Events.Count > 0) { bool success = true; MyBufferedEvent e = eventsBuffer.Events.Peek(); if (e.IsBarrier) { success = this.ProcessBarrierEvent(targetObjectId, e, eventHandler, isBlockedHandler); } else { // If you have blocking entity id, than try to check if it has your barrier on top, // If yes, than process yourself, and put the other id to process later. // If no, than process that id first, as you cannot proceede without it. if (e.BlockingObjectId.IsValid) { success = this.ProcessBlockingEvent(targetObjectId, e, caller, eventHandler, isBlockedHandler, ref postProcessQueue); } else { eventHandler(e.Stream, e.TargetObjectId, e.BlockingObjectId, e.EventId, e.Sender); } if (success) { eventsBuffer.Events.Dequeue(); ReturnEvent(e); } } if(!success) { eventsBuffer.IsProcessing = false; return false; } } return true; }
public void ProcessEvents(NetworkId objectInstance, Handler handler) { List<BufferedEvent> events; if(m_buffer.TryGetValue(objectInstance, out events)) { foreach(var e in events) { handler(e.Stream, e.ObjectInstance, e.EventId, e.Sender); ReturnEvent(e); } events.Clear(); ReturnList(events); } m_buffer.Remove(objectInstance); }
/// <summary> /// Process barrier event. /// </summary> /// <param name="targetObjectId">Target of the barrier event.</param> /// <param name="eventToProcess">Event to process.</param> /// <param name="eventHandler">Handler for processing event.</param> /// <param name="isBlockedHandler">Handler for checking if processing of events should be canceled.</param> /// <returns>True if success.</returns> private bool ProcessBarrierEvent(NetworkId targetObjectId, MyBufferedEvent eventToProcess, Handler eventHandler, IsBlockedHandler isBlockedHandler) { if (isBlockedHandler(eventToProcess.TargetObjectId, eventToProcess.BlockingObjectId)) { return false; } bool success = ProcessEvents(eventToProcess.BlockingObjectId, eventHandler, isBlockedHandler, targetObjectId); return success; }
private void AddNetworkObject(NetworkId networkID, IMyNetObject obj) { IMyNetObject foundObj; if (!m_networkIDToObject.TryGetValue(networkID, out foundObj)) { m_networkIDToObject.Add(networkID, obj); m_objectToNetworkID.Add(obj, networkID); var proxyTarget = obj as IMyProxyTarget; if (proxyTarget != null) { Debug.Assert(proxyTarget.Target != null, "IMyProxyTarget.Target is null!"); if (proxyTarget.Target != null) { m_proxyToTarget.Add(proxyTarget.Target, proxyTarget); } } } else { if (obj != null && foundObj != null) { MyLog.Default.WriteLine("Replicated object already exists adding : " + obj.ToString() + " existing : " + foundObj.ToString() + " id : " + networkID.ToString()); } Debug.Fail("Replicated object already exists!"); } }
protected void AddNetworkObjectClient(NetworkId networkId, IMyNetObject obj) { Debug.Assert(!m_isNetworkAuthority); AddNetworkObject(networkId, obj); }
private void AddNetworkObject(NetworkId networkID, IMyNetObject obj) { IMyNetObject foundObj; if (!m_networkIDToObject.TryGetValue(networkID, out foundObj)) { m_networkIDToObject.Add(networkID, obj); m_objectToNetworkID.Add(obj, networkID); var proxyTarget = obj as IMyProxyTarget; if (proxyTarget != null) { Debug.Assert(proxyTarget.Target != null, "IMyProxyTarget.Target is null!"); if (proxyTarget.Target != null) { m_proxyToTarget.Add(proxyTarget.Target, proxyTarget); } } } else { Debug.Fail("Replicated object already exists!"); } }
protected void RemoveNetworkedObject(NetworkId networkID, IMyNetObject obj) { bool removedId = m_objectToNetworkID.Remove(obj); bool removedObj = m_networkIDToObject.Remove(networkID); Debug.Assert(removedId && removedObj, "Networked object was not removed because it was not in collection"); var proxyTarget = obj as IMyProxyTarget; if (proxyTarget != null) { bool removedProxy = false; if (proxyTarget.Target != null) { removedProxy = m_proxyToTarget.Remove(proxyTarget.Target); } Debug.Assert(removedProxy, "Network object proxy was not removed because it was not in collection"); } m_networkIdGenerator.Return(networkID.Value); }
public bool TryGetNetworkIdByObject(IMyNetObject obj, out NetworkId networkId) { return m_objectToNetworkID.TryGetValue(obj, out networkId); }
public IMyNetObject GetObjectByNetworkId(NetworkId id) { return m_networkIDToObject.GetValueOrDefault(id); }
/// <summary> /// Process blocking event. /// </summary> /// <param name="targetObjectId">Target object id for which to process.</param> /// <param name="eventToProcess">Event to be processed.</param> /// <param name="caller">Parent Network id from which this is called. Set NetworkId.Invalid if no parent.</param> /// <param name="eventHandler">Handler for processing event.</param> /// <param name="isBlockedHandler">Handler for checking if processing of events should be canceled.</param> /// <param name="postProcessQueue">Queue that should be post processed.</param> /// <returns>True if was success.</returns> private bool ProcessBlockingEvent(NetworkId targetObjectId, MyBufferedEvent eventToProcess, NetworkId caller, Handler eventHandler, IsBlockedHandler isBlockedHandler, ref Queue<NetworkId> postProcessQueue) { if (isBlockedHandler(eventToProcess.TargetObjectId, eventToProcess.BlockingObjectId)) { return false; } bool result = this.TryLiftBarrier(eventToProcess.BlockingObjectId); // If success than we can proceede with blocking event. // If not, that means barrier holder have some events before actual barrier. Then we need to process that first. if (result) { eventHandler(eventToProcess.Stream, eventToProcess.TargetObjectId, eventToProcess.BlockingObjectId, eventToProcess.EventId, eventToProcess.Sender); if (eventToProcess.BlockingObjectId.IsValid && !eventToProcess.BlockingObjectId.Equals(caller)) postProcessQueue.Enqueue(eventToProcess.BlockingObjectId); } else { bool success = ProcessEvents(eventToProcess.BlockingObjectId, eventHandler, isBlockedHandler, targetObjectId); return success; } return true; }
public BoltEntity PlayerFromId(NetworkId id) => Scene.SceneTracker.allPlayerEntities.FirstOrDefault(ent => ent.networkId == id);
/// <summary> /// Checks if network id is blocked by other network id. /// </summary> /// <param name="networkId">Target network id.</param> /// <param name="blockedNetId">Blocking network id.</param> /// <returns></returns> private bool IsBlocked(NetworkId networkId, NetworkId blockedNetId) { bool anyReplPending = m_pendingReplicables.ContainsKey(networkId) || m_pendingReplicables.ContainsKey(blockedNetId); bool anyDoesNotExist = GetObjectByNetworkId(networkId) == null || (blockedNetId.IsValid && GetObjectByNetworkId(blockedNetId) == null); if (networkId.IsValid && (anyReplPending || anyDoesNotExist)) { return true; } return false; }
protected override void ProcessEvent(BitStream stream, NetworkId networkId, uint eventId, EndpointId sender) { if (networkId.IsValid && m_pendingReplicables.ContainsKey(networkId)) { m_eventBuffer.EnqueueEvent(stream, networkId, eventId, sender); } else { base.ProcessEvent(stream, networkId, eventId, sender); } }
protected override void ProcessEvent(BitStream stream, NetworkId networkId, NetworkId blockedNetId, uint eventId, EndpointId sender) { LastMessageFromServer = DateTime.UtcNow; // Check if any of them is not blocked already. bool anyContainsEvents = m_eventBuffer.ContainsEvents(networkId) || m_eventBuffer.ContainsEvents(blockedNetId); if (this.IsBlocked(networkId, blockedNetId) || anyContainsEvents) { m_eventBuffer.EnqueueEvent(stream, networkId, blockedNetId, eventId, sender); // Only enqueue barrier if blocking network id is set if(blockedNetId.IsValid) m_eventBuffer.EnqueueBarrier(blockedNetId, networkId); } else { base.ProcessEvent(stream, networkId, blockedNetId, eventId, sender); } }
public void RemoveEvents(NetworkId objectInstance) { // To correctly return everything into pools ProcessEvents(objectInstance, m_emptyHandler); }
/// <summary> /// Marks replicable as successfully created, ready to receive events and state groups data. /// </summary> void SetReplicableReady(NetworkId networkId, IMyReplicable replicable, bool loaded) { MyPendingReplicable pendingReplicable; if (m_pendingReplicables.TryGetValue(networkId, out pendingReplicable)) { m_pendingReplicables.Remove(networkId); if (loaded) { var ids = pendingReplicable.StateGroupIds; AddNetworkObjectClient(networkId, replicable); using (m_tmpGroups) { IMyStreamableReplicable streamable = replicable as IMyStreamableReplicable; if (streamable != null && pendingReplicable.IsStreaming) { var group = streamable.GetStreamingStateGroup(); m_tmpGroups.Add(group); } replicable.GetStateGroups(m_tmpGroups); Debug.Assert(ids.Count == m_tmpGroups.Count, "Number of state groups on client and server for replicable does not match"); for (int i = 0; i < m_tmpGroups.Count; i++) { if (m_tmpGroups[i] != replicable && m_tmpGroups[i].GroupType != StateGroupEnum.Streamining) { AddNetworkObjectClient(ids[i], m_tmpGroups[i]); } } } m_eventBuffer.ProcessEvents(networkId, m_eventHandler, m_isBlockedHandler, NetworkId.Invalid); } else { MyLog.Default.WriteLine("Failed to create replicable ! Type : " + replicable.ToString()); m_eventBuffer.RemoveEvents(networkId); IMyStreamableReplicable streamable = replicable as IMyStreamableReplicable; if (streamable != null && pendingReplicable.IsStreaming) { var group = streamable.GetStreamingStateGroup(); group.Destroy(); NetworkId streaingGroupId; if (TryGetNetworkIdByObject(group, out streaingGroupId)) { RemoveNetworkedObject(group); } MyLog.Default.WriteLine("removing streaming group for not loaded replicable !"); } } m_sendStream.ResetWrite(); m_sendStream.WriteNetworkId(networkId); m_sendStream.WriteBool(loaded); m_callback.SendReplicableReady(m_sendStream); } else { m_pendingReplicables.Remove(networkId); using (m_tmpGroups) { IMyStreamableReplicable streamable = replicable as IMyStreamableReplicable; if (streamable != null && streamable.NeedsToBeStreamed) { var group = streamable.GetStreamingStateGroup(); m_tmpGroups.Add(group); MyLog.Default.WriteLine("removing streaming group for not loaded replicable !" ); } replicable.GetStateGroups(m_tmpGroups); foreach (var g in m_tmpGroups) { if (g != null) // when terminal repblicable fails to attach to block its state group is null becouase its created inside hook method. { g.Destroy(); } } } replicable.OnDestroy(); } }
public void EnqueueEvent(BitStream stream, NetworkId objectInstance, uint eventId, EndpointId sender) { int requiredByteSize = stream.ByteLength - stream.BytePosition + 1; var e = ObtainEvent(); e.Stream.ResetWrite(); e.Stream.WriteBitStream(stream); e.Stream.ResetRead(); e.ObjectInstance = objectInstance; e.EventId = eventId; e.Sender = sender; List<BufferedEvent> events; if (!m_buffer.TryGetValue(objectInstance, out events)) { events = ObtainList(); m_buffer.Add(objectInstance, events); } events.Add(e); }
public static void WriteNetworkId(this VRage.Library.Collections.BitStream stream, NetworkId networkId) { stream.WriteVariant((uint)networkId.Value); }
protected IMyNetObject RemoveNetworkedObject(NetworkId networkID) { IMyNetObject obj; if (m_networkIDToObject.TryGetValue(networkID, out obj)) { RemoveNetworkedObject(networkID, obj); } else { Debug.Fail("RemoveNetworkedObject, object not found!"); } return obj; }
public void RemoveFixedObject(uint id, IMyNetObject obj) { var netId = new NetworkId(id); m_fixedObjects.Remove(obj); RemoveNetworkedObject(netId, obj); }