Пример #1
0
		public IEncodable Decode(BinaryInput stream) {
			this.Name = stream.ReadString();
			this.Author = stream.ReadString();

			this.Width = stream.ReadInt32();
			this.Height = stream.ReadInt32();

			this.Tiles = new MockupTile[Width][][];
			for (int i = 0; i < Width; i++) {
				Tiles[i] = new MockupTile[Height][];
				for (int j = 0; j < Height; j++) {
					Tiles[i][j] = new MockupTile[Map.LayerCount];
				}
			}

			int w = Width;
			int h = Height;

			this.Tilesets = stream.ReadList<MockupTileset>();

			for (int i = 0; i < w; i++) {
				for (int j = 0; j < h; j++) {
					for (int k = 0; k < Map.LayerCount; k++) {
						Tiles[i][j][k] = stream.ReadObject<MockupTile>();
					}
				}
			}

			int c = stream.ReadInt32();
			for (int i = 0; i < c; i++) {
				Tuple<Int32, Vector2> t = new Tuple<Int32, Vector2>(stream.ReadInt32(), stream.ReadVector2());
				Entities.Add(t);
			}
			return this;
		}
Пример #2
0
        public static NamedCompound DecodeCompound(BinaryInput stream, List <Tuple <string, Type> > GenericChute)
        {
            NamedCompound result = new NamedCompound();

            result.Name = stream.ReadString();
            int             c  = stream.ReadInt32();
            NamedVariableIO io = new NamedVariableIO(stream);

            for (int i = 0; i < c; i++)
            {
                NamedVariable varag = io.Read();
                if (varag != null)
                {
                    result.Tokens.Add(varag);
                }
                else
                {
                    string n    = stream.ReadString();
                    Type   type = null;
                    foreach (Tuple <string, Type> t in GenericChute.Where(t => n == t.Item1))
                    {
                        type = t.Item2;
                    }
                    if (type != null)
                    {
                    }
                }
            }
            return(result);
        }
Пример #3
0
		public IEncodable Decode(BinaryInput stream) {
			this.Name = stream.ReadString();
			this.Author = stream.ReadString();

			this.TilesetFactory = stream.ReadObject<TilesetFactory>();
			this.EntityTemplateFactory = stream.ReadObject<EntityTemplateFactory>();

			this.TilesetContainer = stream.ReadObject<TilesetContainer>();
			this.EntityContainer = stream.ReadObject<EntityContainer>();
			this.UIContainer = stream.ReadObject<UIContainer>();
			this.SpriteLibrary = stream.ReadObject<SpriteLibrary.SpriteLibrary>();
			return this;
		}
Пример #4
0
        public IEncodable Decode(BinaryInput stream)
        {
            this.Name   = stream.ReadString();
            this.Author = stream.ReadString();

            this.TilesetFactory        = stream.ReadObject <TilesetFactory>();
            this.EntityTemplateFactory = stream.ReadObject <EntityTemplateFactory>();

            this.TilesetContainer = stream.ReadObject <TilesetContainer>();
            this.EntityContainer  = stream.ReadObject <EntityContainer>();
            this.UIContainer      = stream.ReadObject <UIContainer>();
            this.SpriteLibrary    = stream.ReadObject <SpriteLibrary.SpriteLibrary>();
            return(this);
        }
Пример #5
0
        public IEncodable Decode(BinaryInput stream)
        {
            Name = stream.ReadString();
            ID   = stream.ReadInt32();

            EntityType = (EntityType)stream.ReadByte();
            ShadowType = (ShadowType)stream.ReadByte();

            ShadowType = ShadowType.Perspective;

            isSubEntity = stream.ReadBoolean();

            ShadowOffset = stream.ReadInt32();
            stream.ReadInt32();

            CollisionMap = stream.ReadObject <CollisionMap>();
            Texture      = stream.ReadObject <TileableTexture>();

            int c = stream.ReadInt32();

            for (int i = 0; i < c; i++)
            {
                Animations.Add(stream.ReadObject <Animation>());
            }
            return(this);
        }
Пример #6
0
 public IEncodable Decode(BinaryInput stream)
 {
     this.Uid      = stream.ReadString();
     this.Elapsed  = stream.ReadSingle();
     this.Duration = stream.ReadSingle();
     return(this);
 }
Пример #7
0
        public void Compress()
        {
            string inputChars = input.ReadString();
            var    st         = new TrieSymbolTable <int>();

            // initialize symbol table
            for (int i = 0; i < R; i++)
            {
                st.Put("" + (char)i, i);
            }
            int code = R + 1;  // R is codeword for EOF

            while (inputChars.Length > 0)
            {
                string s = st.LongestPrefixOf(inputChars);
                output.Write(st[s], W);
                int t = s.Length;
                if (t < inputChars.Length && code < L)
                {
                    // Add s to symbol table
                    st.Put(inputChars.Substring(0, t + 1), code++);
                }
                // Scan past s in input
                inputChars = inputChars.Substring(t);
            }
            output.Write(R, W);
            output.Close();
        }
Пример #8
0
 public ISerializable Deserialize(BinaryInput input)
 {
     ID = input.ReadInt32();
     Name = input.ReadString();
     TileableTexture = input.ReadObject<TileableTexture>();
     return this;
 }
Пример #9
0
		public IEncodable Decode(BinaryInput stream) {
			this.Name = stream.ReadString();
			this.Unchangeable = stream.ReadBoolean();
			this.Deletable = stream.ReadBoolean();
			this.Texture = stream.ReadTexture();
			return this;
		}
Пример #10
0
        public override IEncodable Decode(BinaryInput stream)
        {
            base.Decode(stream);
            value = stream.ReadString();

            return(this);
        }
Пример #11
0
 public IEncodable Decode(BinaryInput stream)
 {
     this.Name         = stream.ReadString();
     this.Unchangeable = stream.ReadBoolean();
     this.Deletable    = stream.ReadBoolean();
     this.Texture      = stream.ReadTexture();
     return(this);
 }
Пример #12
0
        public IEncodable Decode(BinaryInput stream)
        {
            this.Name   = stream.ReadString();
            this.Author = stream.ReadString();

            this.Width  = stream.ReadInt32();
            this.Height = stream.ReadInt32();

            this.Tiles = new MockupTile[Width][][];
            for (int i = 0; i < Width; i++)
            {
                Tiles[i] = new MockupTile[Height][];
                for (int j = 0; j < Height; j++)
                {
                    Tiles[i][j] = new MockupTile[Map.LayerCount];
                }
            }

            int w = Width;
            int h = Height;

            this.Tilesets = stream.ReadList <MockupTileset>();

            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    for (int k = 0; k < Map.LayerCount; k++)
                    {
                        Tiles[i][j][k] = stream.ReadObject <MockupTile>();
                    }
                }
            }

            int c = stream.ReadInt32();

            for (int i = 0; i < c; i++)
            {
                Tuple <Int32, Vector2> t = new Tuple <Int32, Vector2>(stream.ReadInt32(), stream.ReadVector2());
                Entities.Add(t);
            }
            return(this);
        }
Пример #13
0
 public ISerializable Deserialize(BinaryInput input)
 {
     Name = input.ReadString();
     TimePerFrame = input.ReadSingle();
     Frames = input.ReadList<KeyFrame>();
     AnimationFlag = (AnimationFlags) input.ReadByte();
     FlipEffect = (SpriteEffects) input.ReadByte();
     Rotation = input.ReadSingle();
     return this;
 }
Пример #14
0
		public static NamedCompound DecodeCompound(BinaryInput stream, List<Tuple<string, Type>> GenericChute) {
			NamedCompound result = new NamedCompound();
			result.Name = stream.ReadString();
			int c = stream.ReadInt32();
			NamedVariableIO io = new NamedVariableIO(stream);
			for (int i = 0; i < c; i++) {
				NamedVariable varag= io.Read();
				if (varag != null) result.Tokens.Add(varag);
				else {
					string n = stream.ReadString();
					Type type = null;
					foreach (Tuple<string, Type> t in GenericChute.Where(t => n == t.Item1)) {
						type = t.Item2;
					}
					if (type != null) {
					}
				}
			}
			return result;
		}
Пример #15
0
		public IEncodable Decode(BinaryInput stream) {
			this.Name = stream.ReadString();
			int tilesCount = stream.ReadInt32();

			for (int i = 0; i < tilesCount; i++) {
				Tiles.Add(stream.ReadObject<Tile>());
			}

			this.Texture = stream.ReadObject<TileableTexture>();

			return this;
		}
Пример #16
0
		public IEncodable Decode(BinaryInput stream) {
			this.Name = stream.ReadString();
			this.TimePerFrame = stream.ReadSingle();
			this.Flags = (AnimationFlags) stream.ReadByte();

			int count = stream.ReadInt32();
			for (int i = 0; i < count; i++) {
				this.Indices.Add(stream.ReadInt32());
			}

			return this;
		}
Пример #17
0
        public IEncodable Decode(BinaryInput stream)
        {
            this.Name = stream.ReadString();
            int tilesCount = stream.ReadInt32();

            for (int i = 0; i < tilesCount; i++)
            {
                Tiles.Add(stream.ReadObject <Tile>());
            }

            this.Texture = stream.ReadObject <TileableTexture>();

            return(this);
        }
Пример #18
0
        public IEncodable Decode(BinaryInput stream)
        {
            this.Name         = stream.ReadString();
            this.TimePerFrame = stream.ReadSingle();
            this.Flags        = (AnimationFlags)stream.ReadByte();

            int count = stream.ReadInt32();

            for (int i = 0; i < count; i++)
            {
                this.Indices.Add(stream.ReadInt32());
            }

            return(this);
        }
Пример #19
0
        private Player Deserialize(BinaryInput Input)
        {
            IPAddress  PublicAddress  = IPAddress.Parse(Input.ReadString());
            ushort     PublicPort     = Input.ReadUInt16();
            IPEndPoint PublicEndpoint = new IPEndPoint(PublicAddress, PublicPort);

            IPAddress  LocalAddress  = IPAddress.Parse(Input.ReadString());
            ushort     LocalPort     = Input.ReadUInt16();
            IPEndPoint LocalEndpoint = new IPEndPoint(LocalAddress, LocalPort);

            Guid PlayerId = Input.ReadGuid();
            bool LocalPlayer = PlayerId == this.localPlayer.PlayerId;
            int  i, c = (int)Input.ReadUInt();

            KeyValuePair <string, string>[] PlayerMetaInfo = LocalPlayer ? null : new KeyValuePair <string, string> [c];
            string Key, Value;

            for (i = 0; i < c; i++)
            {
                Key   = Input.ReadString();
                Value = Input.ReadString();
                if (!LocalPlayer)
                {
                    PlayerMetaInfo[i] = new KeyValuePair <string, string>(Key, Value);
                }
            }

            if (LocalPlayer)
            {
                return(null);
            }
            else
            {
                return(new Player(PlayerId, PublicEndpoint, LocalEndpoint, PlayerMetaInfo));
            }
        }
Пример #20
0
        public ISerializable Deserialize(BinaryInput input)
        {
            Texture = input.ReadTexture();
            Position = input.ReadVector2();

            int size = input.ReadInt32();
            animations = new Dictionary<string, Animation>(size);
            for (var i = 0; i < size; i++)
            {
                string key = input.ReadString();
                var value = input.ReadObject<Animation>();
                animations.Add(key, value);
            }

            return this;
        }
Пример #21
0
		public IEncodable Decode(BinaryInput stream) {
			Name = stream.ReadString();
			ID = stream.ReadInt32();

			EntityType = (EntityType) stream.ReadByte();
			ShadowType = (ShadowType) stream.ReadByte();

			ShadowType = ShadowType.Perspective;

			isSubEntity = stream.ReadBoolean();

			ShadowOffset = stream.ReadInt32();
			stream.ReadInt32();

			CollisionMap = stream.ReadObject<CollisionMap>();
			Texture = stream.ReadObject<TileableTexture>();

			int c = stream.ReadInt32();
			for (int i = 0; i < c; i++) {
				Animations.Add(stream.ReadObject<Animation>());
			}
			return this;
		}
Пример #22
0
        public virtual IEncodable Decode(BinaryInput stream)
        {
            this.Name      = stream.ReadString();
            this.Deletable = stream.ReadBoolean();

            int c = stream.ReadInt32();

            for (int i = 0; i < c; i++)
            {
                SpriteLibraryDirectory child = stream.ReadObject <SpriteLibraryDirectory>();
                child.Parent = this;
                Directories.Add(child);
            }

            c = stream.ReadInt32();
            for (int i = 0; i < c; i++)
            {
                SpriteLibrarySprite child = stream.ReadObject <SpriteLibrarySprite>();
                child.Parent = this;
                Sprites.Add(child);
            }

            return(this);
        }
Пример #23
0
        private void Peer_OnReceived(object Sender, byte[] Packet)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Player         Player;

            if (Connection.StateObject is null)
            {
                BinaryInput Input = new BinaryInput(Packet);
                Guid        PlayerId;
                IPAddress   PlayerRemoteAddress;
                IPEndPoint  PlayerRemoteEndpoint;

                try
                {
                    PlayerId             = Input.ReadGuid();
                    PlayerRemoteAddress  = IPAddress.Parse(Input.ReadString());
                    PlayerRemoteEndpoint = new IPEndPoint(PlayerRemoteAddress, Input.ReadUInt16());
                }
                catch (Exception)
                {
                    Connection.Dispose();
                    return;
                }

                if (Input.BytesLeft == 0)
                {
                    Packet = null;
                }
                else
                {
                    Packet = Input.GetRemainingData();
                }

                bool AllConnected;

                lock (this.remotePlayersByEndpoint)
                {
                    if (!this.playersById.TryGetValue(PlayerId, out Player))
                    {
                        Connection.Dispose();
                        return;
                    }

                    if (Player.Connection is null)
                    {
                        this.connectionCount++;
                    }
                    else
                    {
                        Player.Connection.Dispose();
                    }

                    Player.Connection         = Connection;
                    Connection.StateObject    = Player;
                    Connection.RemoteEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

                    AllConnected = this.connectionCount + 1 == this.playerCount;
                }

                MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;
                if (h != null)
                {
                    try
                    {
                        h(this, Player);
                    }
                    catch (Exception ex)
                    {
                        Events.Log.Critical(ex);
                    }
                }

                if (AllConnected)
                {
                    this.State = MultiPlayerState.Ready;
                }

                if (Packet is null)
                {
                    return;
                }
            }
            else
            {
                Player = (Player)Connection.StateObject;
            }

            this.GameDataReceived(Player, Connection, Packet);
        }
Пример #24
0
        private void Connection_OnReceived(object Sender, byte[] Packet)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Guid           PlayerId;
            IPAddress      PlayerRemoteAddress;
            IPEndPoint     PlayerRemoteEndpoint;

            try
            {
                BinaryInput Input = new BinaryInput(Packet);

                PlayerId             = Input.ReadGuid();
                PlayerRemoteAddress  = IPAddress.Parse(Input.ReadString());
                PlayerRemoteEndpoint = new IPEndPoint(PlayerRemoteAddress, Input.ReadUInt16());
            }
            catch (Exception)
            {
                Connection.Dispose();
                return;
            }

            Player Player = (Player)Connection.StateObject;

            lock (this.remotePlayersByEndpoint)
            {
                if (!this.playersById.TryGetValue(PlayerId, out Player Player2) || Player2.PlayerId != Player.PlayerId)
                {
                    Connection.Dispose();
                    return;
                }

                Player.Connection = Connection;
            }

            Connection.RemoteEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

            Connection.OnReceived -= new BinaryEventHandler(Connection_OnReceived);
            Connection.OnReceived += new BinaryEventHandler(Peer_OnReceived);

            Connection.OnSent += new BinaryEventHandler(Connection_OnSent);

            BinaryOutput Output = new BinaryOutput();

            Output.WriteGuid(this.localPlayer.PlayerId);
            Output.WriteString(this.ExternalAddress.ToString());
            Output.WriteUInt16((ushort)this.ExternalEndpoint.Port);

            Connection.SendTcp(Output.GetPacket());

            MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;

            if (h != null)
            {
                try
                {
                    h(this, Player);
                }
                catch (Exception ex)
                {
                    Events.Log.Critical(ex);
                }
            }
        }
Пример #25
0
        public IEncodable Decode(BinaryInput stream)
        {
            stream.GraphicsDevice = EditorEngine.Instance.GraphicsDevice;

            RegionName   = stream.ReadString();
            RegionAuthor = stream.ReadString();

            World world = EditorEngine.Instance.CreateRegion(RegionName);

            world.TilesetContainer.Decode(stream);
            world.EntityContainer.Decode(stream);
            world.EntityTemplateFactory.Decode(stream);
            world.TilesetFactory.Decode(stream);
            world.UIContainer.Decode(stream);
            world.SpriteLibrary.Decode(stream);

            this.RootNode = new TreeNode(RegionName);
            TreeNode lastNode    = null;
            TreeNode currentNode = RootNode;

            int c = stream.ReadInt32();

            for (int i = 0; i < c; i++)
            {
                int code = stream.ReadInt32();
                switch (code)
                {
                case 0x01:
                    string   text = stream.ReadString();
                    TreeNode node = new TreeNode(text);
                    currentNode.Nodes.Add(node);
                    lastNode = node;
                    break;

                case 0x02:
                    currentNode = lastNode;
                    break;

                case 0x03:
                    currentNode = currentNode.Parent;
                    break;

                case 0x04:
                    /*RECREATE FROM DETAILS*/
                    Map m = new Map(EditorEngine.Instance.World.EntityFactory);

                    m.Name   = stream.ReadString();
                    m.Author = stream.ReadString();
                    m.Width  = stream.ReadInt32();
                    m.Height = stream.ReadInt32();

                    m.Tiles = new MockupTile[m.Width][][];
                    for (int x = 0; x < m.Width; x++)
                    {
                        m.Tiles[x] = new MockupTile[m.Height][];
                        for (int y = 0; y < m.Height; y++)
                        {
                            m.Tiles[x][y] = new MockupTile[Map.LayerCount];
                        }
                    }

                    /* READ ALL MOCKUP TILESETS */
                    int c1 = stream.ReadInt32();
                    for (int j = 0; j < c1; j++)
                    {
                        string name = stream.ReadString();
                        m.Tilesets.Add(new MockupTileset(world, EditorEngine.Instance.GetTilesetIndexByName(name)));
                    }

                    m.Fill(-1, 0);

                    Map oldCurrentMap = EditorEngine.Instance.CurrentMap;

                    EditorEngine.Instance.CurrentMap = m;

                    List <byte> visited = new List <byte>();

                    /* READ MOCKUP TILE BEHAVIORS */
                    m.Behaviors = new MockupTileBehavior[m.Width, m.Height];
                    for (int j = 0; j < m.Width * m.Height; j++)
                    {
                        int x = j % m.Width;
                        int y = j / m.Height;

                        m.Behaviors[x, y] = stream.ReadObject <MockupTileBehavior>();
                    }

                    /* READ ACTIONS/REBUILD MAP */
                    ActionManager actionmanager = EditorEngine.Instance.GetActionManager();
                    ActionIO      reader        = new ActionIO(stream);

                    int c2 = stream.ReadInt32();
                    for (int j = 0; j < c2; j++)
                    {
                        IAction act = reader.Read();
                        actionmanager.Execute(act);
                    }

                    /*DATA TREE NODE*/
                    TreeNode node2 = new TreeNode(m.Name);
                    node2.Tag              = m;
                    node2.ImageKey         = "document.png";
                    node2.SelectedImageKey = "document.png";

                    if (currentNode != null)
                    {
                        currentNode.Nodes.Add(node2);
                    }
                    else
                    {
                        Console.WriteLine("WARNING: CurrentNode is null (Project.Decode)");
                    }

                    EditorEngine.Instance.CurrentMap = oldCurrentMap;
                    break;
                }
            }
            return(this);
        }
Пример #26
0
        private async void MqttConnection_OnContentReceived(object Sender, MqttContent Content)
        {
            try
            {
                BinaryInput Input   = Content.DataInput;
                byte        Command = Input.ReadByte();

                switch (Command)
                {
                case 0:                         // Hello
                    string ApplicationName = Input.ReadString();
                    if (ApplicationName != this.applicationName)
                    {
                        break;
                    }

                    Player Player = this.Deserialize(Input);
                    if (Player is null)
                    {
                        break;
                    }

#if LineListener
                    Console.Out.WriteLine("Rx: HELLO(" + Player.ToString() + ")");
#endif
                    IPEndPoint ExpectedEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

                    lock (this.remotePlayersByEndpoint)
                    {
                        this.remotePlayersByEndpoint[ExpectedEndpoint] = Player;
                        this.remotePlayerIPs[ExpectedEndpoint.Address] = true;
                        this.playersById[Player.PlayerId] = Player;

                        this.UpdateRemotePlayersLocked();
                    }

                    MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerAvailable;
                    if (h != null)
                    {
                        try
                        {
                            h(this, Player);
                        }
                        catch (Exception ex)
                        {
                            Events.Log.Critical(ex);
                        }
                    }
                    break;

                case 1:                             // Interconnect
                    ApplicationName = Input.ReadString();
                    if (ApplicationName != this.applicationName)
                    {
                        break;
                    }

                    Player = this.Deserialize(Input);
                    if (Player is null)
                    {
                        break;
                    }

#if LineListener
                    Console.Out.Write("Rx: INTERCONNECT(" + Player.ToString());
#endif
                    int Index = 0;
                    int i, c;
                    LinkedList <Player> Players = new LinkedList <Player>();
                    bool LocalPlayerIncluded    = false;

                    Player.Index = Index++;
                    Players.AddLast(Player);

                    c = (int)Input.ReadUInt();
                    for (i = 0; i < c; i++)
                    {
                        Player = this.Deserialize(Input);
                        if (Player is null)
                        {
#if LineListener
                            Console.Out.Write("," + this.localPlayer.ToString());
#endif
                            this.localPlayer.Index = Index++;
                            LocalPlayerIncluded    = true;
                        }
                        else
                        {
#if LineListener
                            Console.Out.Write("," + Player.ToString());
#endif
                            Player.Index = Index++;
                            Players.AddLast(Player);
                        }
                    }

#if LineListener
                    Console.Out.WriteLine(")");
#endif
                    if (!LocalPlayerIncluded)
                    {
                        break;
                    }

                    this.mqttConnection.Dispose();
                    this.mqttConnection = null;

                    lock (this.remotePlayersByEndpoint)
                    {
                        this.remotePlayersByEndpoint.Clear();
                        this.remotePlayerIPs.Clear();
                        this.remotePlayersByIndex.Clear();
                        this.playersById.Clear();

                        this.remotePlayersByIndex[this.localPlayer.Index] = this.localPlayer;
                        this.playersById[this.localPlayer.PlayerId]       = this.localPlayer;

                        foreach (Player Player2 in Players)
                        {
                            ExpectedEndpoint = Player2.GetExpectedEndpoint(this.p2pNetwork);

                            this.remotePlayersByIndex[Player2.Index]       = Player2;
                            this.remotePlayersByEndpoint[ExpectedEndpoint] = Player2;
                            this.remotePlayerIPs[ExpectedEndpoint.Address] = true;
                            this.playersById[Player2.PlayerId]             = Player2;
                        }

                        this.UpdateRemotePlayersLocked();
                    }

                    this.State = MultiPlayerState.ConnectingPlayers;
                    await this.StartConnecting();

                    break;

                case 2:                             // Bye
                    ApplicationName = Input.ReadString();
                    if (ApplicationName != this.applicationName)
                    {
                        break;
                    }

                    Guid PlayerId               = Input.ReadGuid();
                    lock (this.remotePlayersByEndpoint)
                    {
                        if (!this.playersById.TryGetValue(PlayerId, out Player))
                        {
                            break;
                        }

#if LineListener
                        Console.Out.WriteLine("Rx: BYE(" + Player.ToString() + ")");
#endif
                        ExpectedEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

                        this.playersById.Remove(PlayerId);
                        this.remotePlayersByEndpoint.Remove(ExpectedEndpoint);
                        this.remotePlayersByIndex.Remove(Player.Index);

                        IPAddress ExpectedAddress = ExpectedEndpoint.Address;
                        bool      AddressFound    = false;

                        foreach (IPEndPoint EP in this.remotePlayersByEndpoint.Keys)
                        {
                            if (IPAddress.Equals(EP.Address, ExpectedAddress))
                            {
                                AddressFound = true;
                                break;
                            }
                        }

                        if (!AddressFound)
                        {
                            this.remotePlayerIPs.Remove(ExpectedAddress);
                        }

                        this.UpdateRemotePlayersLocked();
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
            }
        }
Пример #27
0
		private bool ProcessInputPacket()
		{
			try
			{
				BinaryInput Packet = new BinaryInput(this.inputPacket);
				MqttHeader Header = MqttHeader.Parse(Packet);

				switch (Header.ControlPacketType)
				{
					case MqttControlPacketType.CONNECT:
					default:
						throw new Exception("Received command from server that is not handled: " + Header.ControlPacketType.ToString());

					case MqttControlPacketType.CONNACK:
						bool SessionPresent = (Packet.ReadByte() & 1) != 0;
						byte ReturnCode = Packet.ReadByte();

						try
						{
							switch (ReturnCode)
							{
								case 0:
									this.State = MqttState.Connected;
									this.nextPing = DateTime.Now.AddMilliseconds(this.keepAliveSeconds * 500);
									break;

								case 1:
									throw new IOException("Connection Refused, unacceptable protocol version.");

								case 2:
									throw new IOException("Connection Refused, identifier rejected.");

								case 3:
									throw new IOException("Connection Refused, Server unavailable.");

								case 4:
									throw new IOException("Connection Refused, bad user name or password.");

								case 5:
									throw new IOException("Connection Refused, not authorized.");

								default:
									throw new IOException("Unrecognized error code returned: " + ReturnCode.ToString());
							}
						}
						catch (Exception ex)
						{
							this.ConnectionError(ex);
							this.stream.Close();
							this.client.Close();
							return false;
						}
						break;

					case MqttControlPacketType.PINGREQ:
						this.PINGRESP();
						break;

					case MqttControlPacketType.PINGRESP:
						EventHandler h = this.OnPingResponse;
						if (h != null)
						{
							try
							{
								h(this, new EventArgs());
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;

					case MqttControlPacketType.PUBLISH:
						string Topic = Packet.ReadString();
						
						if (Header.QualityOfService > MqttQualityOfService.AtMostOne)
							Header.PacketIdentifier = Packet.ReadUInt16();
						else
							Header.PacketIdentifier = 0;

						int c = Packet.BytesLeft;
						byte[] Data = Packet.ReadBytes(c);
						MqttContent Content = new MqttContent(Header, Topic, Data);

						switch (Header.QualityOfService)
						{
							case MqttQualityOfService.AtMostOne:
								this.ContentReceived(Content);
								break;

							case MqttQualityOfService.AtLeastOne:
								this.PUBACK(Header.PacketIdentifier);
								this.ContentReceived(Content);
								break;

							case MqttQualityOfService.ExactlyOne:
								lock (this.contentCache)
								{
									this.contentCache[Header.PacketIdentifier] = Content;
								}
								this.PUBREC(Header.PacketIdentifier);
								break;
						}
						break;

					case MqttControlPacketType.PUBACK:
						this.PacketDelivered(Header.PacketIdentifier);
						PacketAcknowledgedEventHandler h2 = this.OnPublished;
						if (h2 != null)
						{
							try
							{
								h2(this, Header.PacketIdentifier);
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;

					case MqttControlPacketType.PUBREC:
						this.PacketDelivered(Header.PacketIdentifier);
						this.PUBREL(Header.PacketIdentifier);
						break;

					case MqttControlPacketType.PUBREL:
						lock (this.contentCache)
						{
							if (this.contentCache.TryGetValue(Header.PacketIdentifier, out Content))
								this.contentCache.Remove(Header.PacketIdentifier);
							else
								Content = null;
						}
						this.PUBCOMP(Header.PacketIdentifier);

						if (Content != null)
							this.ContentReceived(Content);
						break;

					case MqttControlPacketType.PUBCOMP:
						this.PacketDelivered(Header.PacketIdentifier);
						h2 = this.OnPublished;
						if (h2 != null)
						{
							try
							{
								h2(this, Header.PacketIdentifier);
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;

					case MqttControlPacketType.SUBACK:
						this.PacketDelivered(Header.PacketIdentifier);
						h2 = this.OnSubscribed;
						if (h2 != null)
						{
							try
							{
								h2(this, Header.PacketIdentifier);
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;

					case MqttControlPacketType.UNSUBACK:
						this.PacketDelivered(Header.PacketIdentifier);
						h2 = this.OnUnsubscribed;
						if (h2 != null)
						{
							try
							{
								h2(this, Header.PacketIdentifier);
							}
							catch (Exception ex)
							{
#if LineListener
								LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
							}
						}
						break;
				}
			}
			catch (Exception ex)
			{
				this.Error(ex);
			}

			return true;
		}
Пример #28
0
        public ISerializable Deserialize(BinaryInput input)
        {
            Name = input.ReadString();

            int tilesetCount = input.ReadInt32();
            Tilesets = new Dictionary<int, Tileset>(tilesetCount);

            for (var i = 0; i < tilesetCount; i++)
            {
                int key = input.ReadInt32();
                var value = input.ReadObject<Tileset>();
                Tilesets.Add(key, value);
            }

            Layers = input.ReadList<Layer>();
            for (var i = 0; i < Layers.Count; i++)
            {
                Layers[i].Map = this;
            }
            return this;
        }
Пример #29
0
 public ISerializable Deserialize(BinaryInput input)
 {
     ConquerDirectory = input.ReadString();
     Effects = input.ReadBoolean();
     return this;
 }
Пример #30
0
		public IEncodable Decode(BinaryInput stream) {
			this.Uid = stream.ReadString();
			this.Elapsed = stream.ReadSingle();
			this.Duration = stream.ReadSingle();
			return this;
		}
Пример #31
0
        private async Task <bool> Connection_OnReceived(object Sender, byte[] Buffer, int Offset, int Count)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Guid           PlayerId;
            IPAddress      PlayerRemoteAddress;
            IPEndPoint     PlayerRemoteEndpoint;

            try
            {
                BinaryInput Input = new BinaryInput(BinaryTcpClient.ToArray(Buffer, Offset, Count));

                PlayerId             = Input.ReadGuid();
                PlayerRemoteAddress  = IPAddress.Parse(Input.ReadString());
                PlayerRemoteEndpoint = new IPEndPoint(PlayerRemoteAddress, Input.ReadUInt16());
            }
            catch (Exception)
            {
                Connection.Dispose();
                return(true);
            }

            Player Player = (Player)Connection.StateObject;

            lock (this.remotePlayersByEndpoint)
            {
                if (!this.playersById.TryGetValue(PlayerId, out Player Player2) || Player2.PlayerId != Player.PlayerId)
                {
                    Connection.Dispose();
                    return(true);
                }

                Player.Connection = Connection;
            }

            Connection.RemoteEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

            Connection.OnReceived -= this.Connection_OnReceived;
            Connection.OnReceived += this.Peer_OnReceived;
            Connection.OnSent     += this.Connection_OnSent;

            BinaryOutput Output = new BinaryOutput();

            Output.WriteGuid(this.localPlayer.PlayerId);
            Output.WriteString(this.ExternalAddress.ToString());
            Output.WriteUInt16((ushort)this.ExternalEndpoint.Port);

            await Connection.SendTcp(Output.GetPacket());

            MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;

            if (!(h is null))
            {
                try
                {
                    await h(this, Player);
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
            }

            return(true);
        }
Пример #32
0
		public IEncodable Decode(BinaryInput stream) {
			this.Name = stream.ReadString();
			this.Code = stream.ReadString();
			return this;
		}
Пример #33
0
 public IEncodable Decode(BinaryInput stream)
 {
     this.Name = stream.ReadString();
     this.Code = stream.ReadString();
     return(this);
 }
Пример #34
0
		public IEncodable Decode(BinaryInput stream) {
			stream.GraphicsDevice = EditorEngine.Instance.GraphicsDevice;

			RegionName = stream.ReadString();
			RegionAuthor = stream.ReadString();

			World world = EditorEngine.Instance.CreateRegion(RegionName);

			world.TilesetContainer.Decode(stream);
			world.EntityContainer.Decode(stream);
			world.EntityTemplateFactory.Decode(stream);
			world.TilesetFactory.Decode(stream);
			world.UIContainer.Decode(stream);
			world.SpriteLibrary.Decode(stream);

			this.RootNode = new TreeNode(RegionName);
			TreeNode lastNode = null;
			TreeNode currentNode = RootNode;

			int c = stream.ReadInt32();
			for (int i = 0; i < c; i++) {
				int code = stream.ReadInt32();
				switch (code) {
					case 0x01:
						string text = stream.ReadString();
						TreeNode node = new TreeNode(text);
						currentNode.Nodes.Add(node);
						lastNode = node;
						break;
					case 0x02:
						currentNode = lastNode;
						break;
					case 0x03:
						currentNode = currentNode.Parent;
						break;
					case 0x04:
						/*RECREATE FROM DETAILS*/
						Map m = new Map(EditorEngine.Instance.World.EntityFactory);

						m.Name = stream.ReadString();
						m.Author = stream.ReadString();
						m.Width = stream.ReadInt32();
						m.Height = stream.ReadInt32();

						m.Tiles = new MockupTile[m.Width][][];
						for (int x = 0; x < m.Width; x++) {
							m.Tiles[x] = new MockupTile[m.Height][];
							for (int y = 0; y < m.Height; y++) {
								m.Tiles[x][y] = new MockupTile[Map.LayerCount];
							}
						}

						/* READ ALL MOCKUP TILESETS */
						int c1 = stream.ReadInt32();
						for (int j = 0; j < c1; j++) {
							string name = stream.ReadString();
							m.Tilesets.Add(new MockupTileset(world, EditorEngine.Instance.GetTilesetIndexByName(name)));
						}

						m.Fill(-1, 0);

						Map oldCurrentMap = EditorEngine.Instance.CurrentMap;

						EditorEngine.Instance.CurrentMap = m;

						List<byte> visited = new List<byte>();

						/* READ MOCKUP TILE BEHAVIORS */
						m.Behaviors = new MockupTileBehavior[m.Width,m.Height];
						for (int j = 0; j < m.Width * m.Height; j++) {
							int x = j % m.Width;
							int y = j / m.Height;

							m.Behaviors[x, y] = stream.ReadObject<MockupTileBehavior>();
						}

						/* READ ACTIONS/REBUILD MAP */
						ActionManager actionmanager = EditorEngine.Instance.GetActionManager();
						ActionIO reader = new ActionIO(stream);

						int c2 = stream.ReadInt32();
						for (int j = 0; j < c2; j++) {
							IAction act = reader.Read();
							actionmanager.Execute(act);
						}

						/*DATA TREE NODE*/
						TreeNode node2 = new TreeNode(m.Name);
						node2.Tag = m;
						node2.ImageKey = "document.png";
						node2.SelectedImageKey = "document.png";

						if (currentNode != null) currentNode.Nodes.Add(node2);
						else Console.WriteLine("WARNING: CurrentNode is null (Project.Decode)");

						EditorEngine.Instance.CurrentMap = oldCurrentMap;
						break;
				}
			}
			return this;
		}
Пример #35
0
        public virtual IEncodable Decode(BinaryInput stream)
        {
            name = stream.ReadString();

            return(this);
        }
Пример #36
0
		public virtual IEncodable Decode(BinaryInput stream) {
			this.Name = stream.ReadString();
			this.Deletable = stream.ReadBoolean();

			int c = stream.ReadInt32();
			for (int i = 0; i < c; i++) {
				SpriteLibraryDirectory child = stream.ReadObject<SpriteLibraryDirectory>();
				child.Parent = this;
				Directories.Add(child);
			}

			c = stream.ReadInt32();
			for (int i = 0; i < c; i++) {
				SpriteLibrarySprite child = stream.ReadObject<SpriteLibrarySprite>();
				child.Parent = this;
				Sprites.Add(child);
			}

			return this;
		}
Пример #37
0
 public ISerializable Deserialize(BinaryInput input)
 {
     ConquerDirectory = input.ReadString();
     Effects          = input.ReadBoolean();
     return(this);
 }
Пример #38
0
        public static void Main(string[] args)
        {
            ManualResetEvent Terminated = new ManualResetEvent(false);

            Initialize();

            Console.Out.WriteLine("Move the mouse to move the pointer on the screen.");
            Console.Out.WriteLine("Press left mouse button while moving to draw.");
            Console.Out.WriteLine("Press the ESC key to close the application.");
            Console.Out.WriteLine("You will be able to see what others draw as well.");

            OnKeyDown += (sender, e) =>
            {
                if (e.Key == Key.Escape || (e.Key == Key.C && e.Control))
                {
                    Terminated.Set();
                }
            };

            FillRectangle(0, 0, ScreenWidth, ScreenHeight, C64Colors.Blue);

            int          PointerTexture = AddSpriteTexture(GetResourceBitmap("Pointer.png"), System.Drawing.Color.FromArgb(0, 0, 255), true);
            Point        P       = GetMousePointer();
            Point        LastP   = P;
            Sprite       Pointer = CreateSprite(P.X, P.Y, PointerTexture);
            Random       Rnd     = new System.Random();
            int          R       = Rnd.Next(128, 255);
            int          G       = Rnd.Next(128, 255);
            int          B       = Rnd.Next(128, 255);
            Color        Color   = Color.FromArgb(R, G, B);
            bool         Draw    = false;
            BinaryOutput Payload;

            using (MqttConnection MqttConnection = ConnectToMqttServer("iot.eclipse.org", false, string.Empty, string.Empty))
            {
                WriteLine("<" + MqttConnection.State.ToString() + ">", C64Colors.LightGreen);

                MqttConnection.TrustServer = true;

                MqttConnection.OnConnectionError += (sender, ex) =>
                {
                    WriteLine("Unable to connect:", C64Colors.Red);
                };

                MqttConnection.OnError += (sender, ex) =>
                {
                    WriteLine(ex.Message, C64Colors.Red);
                };

                MqttConnection.OnStateChanged += (sender, state) =>
                {
                    WriteLine("<" + MqttConnection.State.ToString() + ">", C64Colors.LightGreen);

                    if (state == MqttState.Connected)
                    {
                        MqttConnection.SUBSCRIBE("RetroSharp/Examples/Networking/MultiUserDraw");
                    }
                };

                OnMouseMove += (sender, e) =>
                {
                    P = e.Position;
                    Pointer.SetPosition(P);

                    int DX = P.X - RasterWidth / 2;
                    int DY = P.Y - RasterHeight / 2;

                    Pointer.Angle = 90 + 22.5 + System.Math.Atan2(DY, DX) * 180 / System.Math.PI;

                    if (Draw)
                    {
                        Payload = new BinaryOutput();
                        Payload.WriteString(MqttConnection.ClientId);
                        Payload.WriteInt(LastP.X);
                        Payload.WriteInt(LastP.Y);
                        Payload.WriteInt(P.X);
                        Payload.WriteInt(P.Y);
                        Payload.WriteColor(Color);

                        MqttConnection.PUBLISH("RetroSharp/Examples/Networking/MultiUserDraw", MqttQualityOfService.AtMostOne, false, Payload);

                        DrawLine(LastP.X, LastP.Y, P.X, P.Y, Color);
                    }

                    LastP = P;
                };

                OnMouseDown += (sender, e) =>
                {
                    Draw = e.LeftButton;
                };

                OnMouseUp += (sender, e) =>
                {
                    Draw = e.LeftButton;
                };

                MqttConnection.OnContentReceived += (sender, Content) =>
                {
                    BinaryInput Input    = Content.DataInput;
                    string      ClientId = Input.ReadString();
                    if (ClientId != MqttConnection.ClientId)
                    {
                        int   X1 = (int)Input.ReadInt();
                        int   Y1 = (int)Input.ReadInt();
                        int   X2 = (int)Input.ReadInt();
                        int   Y2 = (int)Input.ReadInt();
                        Color cl = Input.ReadColor();

                        DrawLine(X1, Y1, X2, Y2, cl);
                    }
                };

                while (!Terminated.WaitOne(1000))
                {
                    ;
                }
            }

            Terminate();
        }
Пример #39
0
        private bool ProcessInputPacket()
        {
            try
            {
                BinaryInput Packet = new BinaryInput(this.inputPacket);
                MqttHeader  Header = MqttHeader.Parse(Packet);

                switch (Header.ControlPacketType)
                {
                case MqttControlPacketType.CONNECT:
                default:
                    throw new Exception("Received command from server that is not handled: " + Header.ControlPacketType.ToString());

                case MqttControlPacketType.CONNACK:
                    bool SessionPresent = (Packet.ReadByte() & 1) != 0;
                    byte ReturnCode     = Packet.ReadByte();

                    try
                    {
                        switch (ReturnCode)
                        {
                        case 0:
                            this.State    = MqttState.Connected;
                            this.nextPing = DateTime.Now.AddMilliseconds(this.keepAliveSeconds * 500);
                            break;

                        case 1:
                            throw new IOException("Connection Refused, unacceptable protocol version.");

                        case 2:
                            throw new IOException("Connection Refused, identifier rejected.");

                        case 3:
                            throw new IOException("Connection Refused, Server unavailable.");

                        case 4:
                            throw new IOException("Connection Refused, bad user name or password.");

                        case 5:
                            throw new IOException("Connection Refused, not authorized.");

                        default:
                            throw new IOException("Unrecognized error code returned: " + ReturnCode.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        this.ConnectionError(ex);
                        this.stream.Close();
                        this.client.Close();
                        return(false);
                    }
                    break;

                case MqttControlPacketType.PINGREQ:
                    this.PINGRESP();
                    break;

                case MqttControlPacketType.PINGRESP:
                    EventHandler h = this.OnPingResponse;
                    if (!(h is null))
                    {
                        try
                        {
                            h(this, new EventArgs());
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;

                case MqttControlPacketType.PUBLISH:
                    string Topic = Packet.ReadString();

                    if (Header.QualityOfService > MqttQualityOfService.AtMostOne)
                    {
                        Header.PacketIdentifier = Packet.ReadUInt16();
                    }
                    else
                    {
                        Header.PacketIdentifier = 0;
                    }

                    int         c       = Packet.BytesLeft;
                    byte[]      Data    = Packet.ReadBytes(c);
                    MqttContent Content = new MqttContent(Header, Topic, Data);

                    switch (Header.QualityOfService)
                    {
                    case MqttQualityOfService.AtMostOne:
                        this.ContentReceived(Content);
                        break;

                    case MqttQualityOfService.AtLeastOne:
                        this.PUBACK(Header.PacketIdentifier);
                        this.ContentReceived(Content);
                        break;

                    case MqttQualityOfService.ExactlyOne:
                        lock (this.contentCache)
                        {
                            this.contentCache[Header.PacketIdentifier] = Content;
                        }
                        this.PUBREC(Header.PacketIdentifier);
                        break;
                    }
                    break;

                case MqttControlPacketType.PUBACK:
                    this.PacketDelivered(Header.PacketIdentifier);
                    PacketAcknowledgedEventHandler h2 = this.OnPublished;
                    if (!(h2 is null))
                    {
                        try
                        {
                            h2(this, Header.PacketIdentifier);
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;

                case MqttControlPacketType.PUBREC:
                    this.PacketDelivered(Header.PacketIdentifier);
                    this.PUBREL(Header.PacketIdentifier);
                    break;

                case MqttControlPacketType.PUBREL:
                    lock (this.contentCache)
                    {
                        if (this.contentCache.TryGetValue(Header.PacketIdentifier, out Content))
                        {
                            this.contentCache.Remove(Header.PacketIdentifier);
                        }
                        else
                        {
                            Content = null;
                        }
                    }
                    this.PUBCOMP(Header.PacketIdentifier);

                    if (!(Content is null))
                    {
                        this.ContentReceived(Content);
                    }
                    break;

                case MqttControlPacketType.PUBCOMP:
                    this.PacketDelivered(Header.PacketIdentifier);
                    h2 = this.OnPublished;
                    if (!(h2 is null))
                    {
                        try
                        {
                            h2(this, Header.PacketIdentifier);
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;

                case MqttControlPacketType.SUBACK:
                    this.PacketDelivered(Header.PacketIdentifier);
                    h2 = this.OnSubscribed;
                    if (!(h2 is null))
                    {
                        try
                        {
                            h2(this, Header.PacketIdentifier);
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;

                case MqttControlPacketType.UNSUBACK:
                    this.PacketDelivered(Header.PacketIdentifier);
                    h2 = this.OnUnsubscribed;
                    if (!(h2 is null))
                    {
                        try
                        {
                            h2(this, Header.PacketIdentifier);
                        }
                        catch (Exception ex)
                        {
#if LineListener
                            LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }

            return(true);
        }