Exemplo n.º 1
0
		public override void Encode(BinaryOutput stream) {
			stream.Write(Directories.Count);
			Directories.ForEach(d => d.Encode(stream));

			stream.Write(Sprites.Count);
			Sprites.ForEach(s => s.Encode(stream));
		}
Exemplo n.º 2
0
 public void Serialize(BinaryOutput output)
 {
     output.Write(TilesetID);
     output.Write(Row);
     output.Write(Col);
     output.Write(X);
     output.Write(Y);
 }
Exemplo n.º 3
0
		public static void DumpGame(World world, BinaryOutput output) {
			new RegionData().Encode(output, world);

			output.Write(world.Maps.Count);
			foreach (Map map in world.Maps) {
				new MapData().Encode(output, map);
			}
		}
Exemplo n.º 4
0
		public void Encode(BinaryOutput stream) {
			stream.Write((byte) Pattern);
			stream.Write((byte) Speed);
			stream.Write(Count);
			stream.Write(CurrentIndex);
			stream.Write(Inverted);
			stream.Write(Movements.Count);
			Movements.ForEach(m => m.Encode(stream));
		}
Exemplo n.º 5
0
		public void Encode(BinaryOutput stream) {
			stream.Write(Name);
			stream.Write(Tiles.Count);

			foreach (Tile tile in Tiles) {
				stream.Write(tile);
			}
			stream.Write(Texture);
		}
Exemplo n.º 6
0
 public void Serialize(BinaryOutput output)
 {
     output.Write(Name);
     output.Write(TimePerFrame);
     output.Write(Frames);
     output.Write((byte) AnimationFlag);
     output.Write((byte) FlipEffect);
     output.Write(Rotation);
 }
Exemplo n.º 7
0
		public void Encode(BinaryOutput stream) {
			stream.Write(spriteindex);
			stream.Write(collidable);
			stream.Write(reflecting);
			stream.Write(animated);
			stream.Write(frames);
			stream.Write(timeperframe);
			stream.Write(DefaultBehavior);
		}
Exemplo n.º 8
0
		public void Encode(BinaryOutput stream) {
			stream.Write(this.Name);
			stream.Write(this.TimePerFrame);
			stream.Write((byte) this.Flags);

			stream.Write(this.Indices.Count);
			foreach (int value in this.Indices) {
				stream.Write(value);
			}
		}
Exemplo n.º 9
0
		public void Encode(BinaryOutput stream, World world) {
			stream.Write(world.Name);
			stream.Write(world.Author ?? "");
			
			world.TilesetFactory.Encode(stream);
			world.EntityTemplateFactory.Encode(stream);

			world.TilesetContainer.Encode(stream);
			world.EntityContainer.Encode(stream);
			world.UIContainer.Encode(stream);
			world.SpriteLibrary.Encode(stream);
		}
Exemplo n.º 10
0
		public void Encode(BinaryOutput stream) {
			stream.Write(Name);
			stream.Write(Tokens.Count);
			NamedVariableIO io = new NamedVariableIO(stream);
			foreach (IEncodable token in Tokens) {
				if (token is NamedVariable) {
					io.Write(token as NamedVariable);
				} else {
					stream.Write(-1);
					stream.Write(token);
				}
			}
		}
Exemplo n.º 11
0
        public void Serialize(BinaryOutput output)
        {
            output.Write(Rows);
            output.Write(Cols);

            for (var i = 0; i < Rows; i++)
            {
                for (var j = 0; j < Cols; j++)
                {
                    output.Write(Tiles[i, j]);
                }
            }
        }
Exemplo n.º 12
0
        public void Serialize(BinaryOutput output)
        {
            output.Write(Name);

            output.Write(Tilesets.Count);
            for (var i = 0; i < Tilesets.Count; i++)
            {
                KeyValuePair<int, Tileset> element = Tilesets.ElementAt(i);
                output.Write(element.Key);
                output.Write(element.Value);
            }

            output.Write(Layers);
        }
Exemplo n.º 13
0
        public void Serialize(BinaryOutput output)
        {
            output.Write(Texture);
            output.Write(Position);

            int size = animations.Count;
            output.Write(size);
            for (var i = 0; i < size; i++)
            {
                KeyValuePair<string, Animation> element = animations.ElementAt(i);
                output.Write(element.Key);
                output.Write(element.Value);
            }
        }
        public byte[] DecompileMethod(MethodDefinition method)
        {
            var binout = new BinaryOutput(this);

            try
            {
                DecompileMethod(method, binout);
            }
            catch (Exception ex)
            {
                binout.Write("Error Decompiling: " + ex.Message);
            }

            return binout.GetOutput();
        }
Exemplo n.º 15
0
		public void BuildGame(Project project, string loc) {
			FileStream stream = File.OpenWrite(loc);
			BinaryOutput output = new BinaryOutput(stream);


			output.Write(project.World.TilesetContainer.Count);
			foreach (Tileset t in project.World.TilesetContainer) {
				output.Write(t);
			}

			output.Write(project.World.EntityContainer.All().Count);
			foreach (EntityTemplate e in project.World.EntityContainer.All()) {
				output.Write(e);
			}


		}
Exemplo n.º 16
0
		public void Encode(BinaryOutput stream) {
			stream.Write(Name);
			stream.Write(ID);

			stream.Write((byte) EntityType);
			stream.Write((byte) ShadowType);

			stream.Write(isSubEntity);

			stream.Write(ShadowOffset);
			stream.Write(0);

			stream.Write(CollisionMap as IEncodable);
			stream.Write(Texture);

			stream.Write(Animations.Count);
			foreach (Animation animation in Animations) {
				stream.Write(animation);
			}
		}
Exemplo n.º 17
0
		public void Encode(BinaryOutput stream, Map map) {
			stream.Write(map.Name);
			stream.Write(map.Author);

			stream.Write(map.Width);
			stream.Write(map.Height);

			stream.Write(map.Tilesets);

			for (int i = 0; i < map.Width; i++) {
				for (int j = 0; j < map.Height; j++) {
					for (int k = 0; k < Map.LayerCount; k++) {
						map.Tiles[i][j][k].Encode(stream);
					}
				}
			}

			stream.Write(map.Entities.Count);
			foreach (MapEntity e in map.Entities) {
				stream.Write(e.TemplateID);
				stream.Write(e.Position);
			}
		}
Exemplo n.º 18
0
		public void Copy() {
			if (this.Initialized) {
				if (EditorEngine.Instance.StateMachine.State == EntityEditorState.Instance) {
					//DataObject obj = new DataObject("aeon_entities", null);
					DataFormats.Format f = DataFormats.GetFormat("aeon_entities");
					IDataObject obj = new DataObject();

					MemoryStream stream = new MemoryStream();
					BinaryOutput bin = new BinaryOutput(stream);

					bin.Write(EntitySelectionTool.Instance.SelectedEntities.Count);
					//write Template index and positions, no actual Entities :>
					EntitySelectionTool.Instance.SelectedEntities.ForEach(e => {
						bin.Write(e.TemplateID);
						bin.Write(e.Position.X);
						bin.Write(e.Position.Y);
					});

					obj.SetData(f.Name, false, stream);
					Clipboard.SetDataObject(obj);
				}
			}
		}
Exemplo n.º 19
0
        static void AssembleStrings(SourceLine line)
        {
            if (!line.OperandHasToken)
            {
                throw new ExpressionException(line.Instruction.Position,
                                              $"Instruction \"{line.InstructionName}\" expects one or more string arguments.");
            }

            line.Assembly = new List <byte>();
            var stringBytes = new List <byte>();
            var uninit      = 0;

            foreach (Token child in line.Operand.Children)
            {
                if (child.Children.Count == 0)
                {
                    throw new ExpressionException(child.Position, $"Expected value for instruction \"{line.InstructionName}\".");
                }

                if (child.Children[0].ToString().Equals("?"))
                {
                    if (child.Children.Count > 1)
                    {
                        Assembler.Log.LogEntry(line, child.Children[1].Position,
                                               $"Unexpected expression \"{child.Children[1].Name}\".");
                    }
                    uninit++;
                    Assembler.Output.AddUninitialized(1);
                }
                else
                {
                    if (StringHelper.ExpressionIsAString(child))
                    {
                        stringBytes.AddRange(Assembler.Encoding.GetBytes(StringHelper.GetString(child)));
                    }
                    else
                    {
                        stringBytes.AddRange(BinaryOutput.ConvertToBytes(Evaluator.Evaluate(child)).ToList());
                    }
                }
            }
            switch (line.InstructionName)
            {
            case ".cstring":
                stringBytes.Add(0x00);
                break;

            case ".pstring":
                if (stringBytes.Count > 255)
                {
                    throw new ExpressionException(line.Operand.Position, $"String expression exceeds the maximum length of \".pstring\" directive.");
                }

                stringBytes.Insert(0, Convert.ToByte(stringBytes.Count));
                break;

            case ".lstring":
            case ".nstring":
                if (stringBytes.Any(b => b > 0x7f))
                {
                    throw new ExpressionException(line.Operand.Position, $"One or more elements in expression \"{line.Operand}\" exceeds maximum value.");
                }
                if (line.InstructionName.Equals(".lstring"))
                {
                    stringBytes       = stringBytes.Select(b => Convert.ToByte(b << 1)).ToList();
                    stringBytes[^ 1] |= 1;
Exemplo n.º 20
0
        public static void Main(string[] _)
        {
            Initialize();

            Guid   PlayerId = Guid.NewGuid();
            string Player1Name;
            string Player2Name;

            Console.Out.WriteLine("Welcome to Mask! (Worms/Tron)");
            Console.Out.WriteLine(new string('-', 70));
            Console.Out.WriteLine("You control the work using the cursor keys.");
            Console.Out.WriteLine("Fire, using SPACE.");
            Console.Out.WriteLine("If you die, press ENTER to restart the game.");
            Console.Out.WriteLine("You can chat during the game.");
            Console.Out.WriteLine("Remember to try to fetch the gifts. You do that by moving into them.");
            Console.Out.WriteLine();
            Console.Out.WriteLine("Hello. What is your name?");
            Player1Name = Player2Name = Console.ReadLine();

            using (MPE = new MultiPlayerEnvironment("Mask", false, "iot.eclipse.org", 1883, false, string.Empty, string.Empty,
                                                    "RetroSharp/Examples/Games/Mask", 2, PlayerId, new KeyValuePair <string, string>("NAME", Player1Name)))
            {
                MPE.OnStateChange += (sender, state) =>
                {
                    switch (state)
                    {
                    case MultiPlayerState.SearchingForGateway:
                        Console.Out.WriteLine("Searching for Internet Gateway.");
                        break;

                    case MultiPlayerState.RegisteringApplicationInGateway:
                        Console.Out.WriteLine("Registering game in gateway.");
                        break;

                    case MultiPlayerState.FindingPlayers:
                        Console.Out.WriteLine("Waiting for another player to connect.");
                        Console.Out.WriteLine("Press ESC to play in single player mode.");
                        OnKeyDown += new KeyEventHandler(MPE_Wait_OnKeyDown);
                        break;

                    case MultiPlayerState.ConnectingPlayers:
                        Console.Out.WriteLine("Connecting to players.");
                        break;
                    }
                };

                MPE.OnPlayerAvailable += (sender, player) =>
                {
                    Console.Out.WriteLine("New player available: " + player["NAME"]);
                    MPE.ConnectPlayers();
                };

                MPE.OnPlayerConnected += (sender, player) =>
                {
                    Player2Name = player["NAME"];
                };

                MPE.OnPlayerDisconnected += (sender, player) =>
                {
                    PlayerMsg(2, "Disconnected");
                    NrPlayers = 1;
                    LocalMachineIsGameServer = true;
                };

                if (MPE.Wait(int.MaxValue))
                {
                    NrPlayers = MPE.PlayerCount;
                    LocalMachineIsGameServer = MPE.LocalPlayerIsFirst;
                }
                else
                {
                    PlayerMsg(2, "Network error");
                    NrPlayers = 1;
                }

                OnKeyDown -= new KeyEventHandler(MPE_Wait_OnKeyDown);

                ManualResetEvent            Done             = new ManualResetEvent(false);
                LinkedList <Shot>           Shots            = new LinkedList <Shot>();
                LinkedList <Explosion>      Explosions       = new LinkedList <Explosion>();
                LinkedList <Present>        Presents         = new LinkedList <Present>();
                LinkedList <PlayerPosition> Player2Positions = new LinkedList <PlayerPosition>();
                Player Player1      = new Player(1, 20, 28, 1, 0, 3, Color.Green, Color.LightGreen, 15);
                Player Player2      = new Player(2, 299, 179, -1, 0, 3, Color.Blue, Color.LightBlue, 15);
                bool   Player1Up    = false;
                bool   Player1Down  = false;
                bool   Player1Left  = false;
                bool   Player1Right = false;
                bool   Player1Fire  = false;
                bool   Player2Up    = false;
                bool   Player2Down  = false;
                bool   Player2Left  = false;
                bool   Player2Right = false;
                bool   Player2Fire  = false;

                Player1.Opponent = Player2;
                Player2.Opponent = Player1;

                Clear();
                FillRectangle(0, 0, 319, 7, Color.FromKnownColor(KnownColor.DimGray));
                SetClipArea(0, 8, 319, 199);

                string s = Player1Name.Length <= 10 ? Player1Name : Player1Name.Substring(0, 10);
                Console.Out.Write(s);

                s = Player2Name.Length <= 10 ? Player2Name : Player2Name.Substring(0, 10);
                GotoXY(ConsoleWidth - s.Length, 0);
                Console.Out.Write(s);

                OnKeyDown += (sender, e) =>
                {
                    switch (e.Key)
                    {
                    case Key.Escape:
                        if (MPE.State == MultiPlayerState.FindingPlayers)
                        {
                            MPE.ConnectPlayers();
                        }
                        else
                        {
                            Done.Set();
                        }
                        break;

                    case Key.C:
                        if (e.Control)
                        {
                            Done.Set();
                        }
                        break;

                    case Key.Up:
                        if (!Player1.Dead && Player1.VY != 1)
                        {
                            Player1Up = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Down = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 0 }, 3);
                            }
                        }
                        break;

                    case Key.Down:
                        if (!Player1.Dead && Player1.VY != -1)
                        {
                            Player1Down = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Up = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 1 }, 3);
                            }
                        }
                        break;

                    case Key.Left:
                        if (!Player1.Dead && Player1.VX != 1)
                        {
                            Player1Left = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Right = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 2 }, 3);
                            }
                        }
                        break;

                    case Key.Right:
                        if (!Player1.Dead && Player1.VX != -1)
                        {
                            Player1Right = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Left = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 3 }, 3);
                            }
                        }
                        break;

                    case Key.Space:
                        if (!Player1.Dead)
                        {
                            Player1Fire = true;

                            if (NrPlayers == 1)
                            {
                                if (!Player2.Dead)
                                {
                                    Player2Fire = true;
                                }
                            }
                            else
                            {
                                MPE.SendUdpToAll(new byte[] { 4 }, 3);
                            }
                        }
                        break;

                    case Key.Enter:
                        if (Player1.Dead)
                        {
                            if (NrPlayers > 1)
                            {
                                MPE.SendUdpToAll(new byte[] { 5 }, 3);
                            }
                            else
                            {
                                lock (Player2Positions)
                                {
                                    Player2Positions.Clear();
                                }

                                Shots.Clear();
                                Explosions.Clear();
                                Presents.Clear();
                                Player1      = new Player(1, 20, 28, 1, 0, 3, Color.Green, Color.LightGreen, 15);
                                Player2      = new Player(2, 299, 179, -1, 0, 3, Color.Blue, Color.LightBlue, 15);
                                Player1Up    = false;
                                Player1Down  = false;
                                Player1Left  = false;
                                Player1Right = false;
                                Player1Fire  = false;

                                Player1.Opponent = Player2;
                                Player2.Opponent = Player1;

                                FillRectangle(0, 8, 319, 199, Color.Black);
                                PlayerMsg(1, string.Empty);
                                PlayerMsg(2, string.Empty);
                            }
                        }
                        break;
                    }
                };

                OnKeyPressed += (sender, e) =>
                {
                    ChatCharacter(1, e.Character);
                    MPE.SendTcpToAll(new byte[] { 10, (byte)(e.Character >> 8), (byte)(e.Character) });
                };

                OnUpdateModel += (sender, e) =>
                {
                    if (LocalMachineIsGameServer && Random() < 0.005)
                    {
                        int x1, y1;

                        do
                        {
                            x1 = Random(30, 285);
                            y1 = Random(38, 165);
                        }while (!Present.CanPlace(x1, y1, x1 + 5, y1 + 5));

                        Presents.AddLast(new Present(x1, y1, x1 + 5, y1 + 5));

                        if (NrPlayers > 1)
                        {
                            BinaryOutput Output = new BinaryOutput();

                            Output.WriteByte(6);
                            Output.WriteInt(x1);
                            Output.WriteInt(y1);

                            MPE.SendUdpToAll(Output.GetPacket(), 3);
                        }
                    }

                    LinkedListNode <Present> PresentObj, NextPresentObj;

                    PresentObj = Presents.First;
                    while (!(PresentObj is null))
                    {
                        NextPresentObj = PresentObj.Next;
                        if (PresentObj.Value.Move())
                        {
                            Presents.Remove(PresentObj);
                        }

                        PresentObj = NextPresentObj;
                    }

                    if (Player1Up)
                    {
                        Player1.Up();
                        Player1Up = false;
                    }
                    else if (Player1Down)
                    {
                        Player1.Down();
                        Player1Down = false;
                    }
                    else if (Player1Left)
                    {
                        Player1.Left();
                        Player1Left = false;
                    }
                    else if (Player1Right)
                    {
                        Player1.Right();
                        Player1Right = false;
                    }

                    if (Player2Up)
                    {
                        Player2.Up();
                        Player2Up = false;
                    }
                    else if (Player2Down)
                    {
                        Player2.Down();
                        Player2Down = false;
                    }
                    else if (Player2Left)
                    {
                        Player2.Left();
                        Player2Left = false;
                    }
                    else if (Player2Right)
                    {
                        Player2.Right();
                        Player2Right = false;
                    }

                    if (!Player1.Dead && Player1.Move())
                    {
                        Explosions.AddLast(new Explosion(Player1.X, Player1.Y, 30, Color.White));
                    }

                    if (!Player2.Dead)
                    {
                        if (NrPlayers == 1)
                        {
                            if (Player2.Move())
                            {
                                Explosions.AddLast(new Explosion(Player2.X, Player2.Y, 30, Color.White));
                            }
                        }
                        else
                        {
                            lock (Player2Positions)
                            {
                                try
                                {
                                    foreach (PlayerPosition P in Player2Positions)
                                    {
                                        Player2.BeforeMove();
                                        Player2.SetPosition(P.X, P.Y, P.VX, P.VY);
                                        Player2.AfterMove();

                                        if (P.Dead)
                                        {
                                            Player2.Die();
                                            Explosions.AddLast(new Explosion(Player2.X, Player2.Y, 30, Color.White));
                                        }
                                    }
                                }
                                finally
                                {
                                    Player2Positions.Clear();
                                }
                            }
                        }
                    }

                    if (Player1Fire)
                    {
                        Player1.Fire(Shots);
                        Player1Fire = false;
                    }

                    if (Player2Fire)
                    {
                        Player2.Fire(Shots);
                        Player2Fire = false;
                    }

                    LinkedListNode <Shot> ShotObj, NextShotObj;

                    ShotObj = Shots.First;
                    while (!(ShotObj is null))
                    {
                        NextShotObj = ShotObj.Next;
                        if (ShotObj.Value.Move())
                        {
                            Shots.Remove(ShotObj);
                            Explosions.AddLast(new Explosion(ShotObj.Value.X, ShotObj.Value.Y, ShotObj.Value.Power, Color.White));
                        }

                        ShotObj = NextShotObj;
                    }

                    LinkedListNode <Explosion> ExplosionObj, NextExplosionObj;

                    ExplosionObj = Explosions.First;
                    while (!(ExplosionObj is null))
                    {
                        NextExplosionObj = ExplosionObj.Next;
                        if (ExplosionObj.Value.Move())
                        {
                            Explosions.Remove(ExplosionObj);
                        }

                        ExplosionObj = NextExplosionObj;
                    }
                };

                MPE.OnGameDataReceived += (sender, e) =>
                {
                    byte Command = e.Data.ReadByte();

                    switch (Command)
                    {
                    case 0:                             // Remote player presses UP
                        if (!Player2.Dead)
                        {
                            Player2Down = true;
                        }
                        break;

                    case 1:                             // Remote player presses DOWN
                        if (!Player2.Dead)
                        {
                            Player2Up = true;
                        }
                        break;

                    case 2:                             // Remote player presses LEFT
                        if (!Player2.Dead)
                        {
                            Player2Right = true;
                        }
                        break;

                    case 3:                             // Remote player presses RIGHT
                        if (!Player2.Dead)
                        {
                            Player2Left = true;
                        }
                        break;

                    case 4:                             // Remote player presses SPACE (Fire)
                        if (!Player2.Dead)
                        {
                            Player2Fire = true;
                        }
                        break;

                    case 5:                             // Remote player presses ENTER (Restart)
                    case 9:                             // Acknowledgement of remote player presses ENTER (Restart)

                        if (Command == 5)
                        {
                            MPE.SendUdpToAll(new byte[] { 9 }, 3);
                        }

                        lock (Player2Positions)
                        {
                            Player2Positions.Clear();
                        }

                        Shots.Clear();
                        Explosions.Clear();
                        Presents.Clear();
                        Player1      = new Player(1, 20, 28, 1, 0, 3, Color.Green, Color.LightGreen, 15);
                        Player2      = new Player(2, 299, 179, -1, 0, 3, Color.Blue, Color.LightBlue, 15);
                        Player1Up    = false;
                        Player1Down  = false;
                        Player1Left  = false;
                        Player1Right = false;
                        Player1Fire  = false;

                        Player1.Opponent = Player2;
                        Player2.Opponent = Player1;

                        FillRectangle(0, 8, 319, 199, Color.Black);
                        PlayerMsg(1, string.Empty);
                        PlayerMsg(2, string.Empty);

                        BorderColor = Color.FromKnownColor(KnownColor.DimGray);
                        break;

                    case 6:                             // New Present
                        int x1 = 315 - (int)e.Data.ReadInt();
                        int y1 = 203 - (int)e.Data.ReadInt();

                        Presents.AddLast(new Present(x1, y1, x1 + 5, y1 + 5));
                        break;

                    case 7:                             // Gift
                        x1 = (int)e.Data.ReadInt();
                        Player2.GetGift(2, x1, null, e.Data);
                        break;

                    case 8:                             // Move player 2
                        lock (Player2Positions)
                        {
                            Player2Positions.AddLast(new PlayerPosition(e.Data));
                        }
                        break;

                    case 10:                                    // chat character
                        char ch = (char)e.Data.ReadUInt16();
                        ChatCharacter(2, ch);
                        break;
                    }
                };

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

            Terminate();
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
0
 public void Encode(BinaryOutput stream)
 {
     //nothing, we need map!
 }
Exemplo n.º 23
0
 /// <summary>
 /// Publishes information on a topic.
 /// </summary>
 /// <param name="Topic">Topic name</param>
 /// <param name="QoS">Quality of service</param>
 /// <param name="Retain">If topic shoudl retain information.</param>
 /// <param name="Data">Binary data to send.</param>
 /// <returns>Packet identifier assigned to data.</returns>
 public int PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, BinaryOutput Data)
 {
     return(this.PUBLISH(Topic, QoS, Retain, false, Data.GetPacket()));
 }
Exemplo n.º 24
0
        public static void Main(string[] args)
        {
            Initialize();

            Console.Out.Write("Host Name (default iot.eclipse.org): ");
            string Host = Console.In.ReadLine();

            if (string.IsNullOrEmpty(Host))
            {
                Console.Out.WriteLine("Using iot.eclipse.org.");
                Host = "iot.eclipse.org";
            }

            Console.Out.WriteLine();
            Console.Out.Write("Port Number (default 1883): ");
            string s = Console.In.ReadLine();
            int    Port;

            if (string.IsNullOrEmpty(s))
            {
                Console.Out.WriteLine("Using port 1883.");
                Port = 1883;
            }
            else
            {
                Port = int.Parse(s);
            }

            Console.Out.WriteLine();

            BinaryOutput Payload;
            int          PacketsLeft = NrTestsPerQoS;

            using (MqttConnection MqttConnection = ConnectToMqttServer("iot.eclipse.org", Port, 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.OnContentReceived += (sender, Content) =>
                {
                    string ClientId = Content.DataInput.ReadString();
                    if (ClientId == sender.ClientId)
                    {
                        DateTime             TP  = Content.DataInput.ReadDateTime();
                        MqttQualityOfService QoS = (MqttQualityOfService)Content.DataInput.ReadByte();
                        Console.Out.WriteLine("Latency: " + (DateTime.Now - TP).TotalMilliseconds + " ms (" + QoS.ToString() + ")");

                        bool Resend;

                        if (--PacketsLeft > 0)
                        {
                            Resend = true;
                        }
                        else if (QoS < MqttQualityOfService.ExactlyOne)
                        {
                            QoS         = (MqttQualityOfService)((int)QoS + 1);
                            PacketsLeft = NrTestsPerQoS;
                            Resend      = true;
                        }
                        else
                        {
                            Resend = false;
                        }

                        if (Resend)
                        {
                            Payload = new BinaryOutput();
                            Payload.WriteString(MqttConnection.ClientId);
                            Payload.WriteDateTime(DateTime.Now);
                            Payload.WriteByte((byte)QoS);

                            MqttConnection.PUBLISH("RetroSharp/Examples/Networking/Latency", QoS, false, Payload);
                        }
                        else
                        {
                            Console.Out.WriteLine("Press ENTER to continue.");
                        }
                    }
                };

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

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

                        Payload = new BinaryOutput();
                        Payload.WriteString(MqttConnection.ClientId);
                        Payload.WriteDateTime(DateTime.Now);
                        Payload.WriteByte((byte)MqttQualityOfService.AtMostOne);

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

                Console.In.ReadLine();
            }

            Terminate();
        }
Exemplo n.º 25
0
 public void Encode(BinaryOutput stream)
 {
     stream.Write(Name);
     stream.Write(Code);
 }
Exemplo n.º 26
0
 public void Encode(BinaryOutput stream)
 {
     stream.Write(Uid);
     stream.Write(Elapsed);
     stream.Write(Duration);
 }
Exemplo n.º 27
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();
        }
Exemplo n.º 28
0
 public static void DumpGame(World world, Stream stream)
 {
     using (BinaryOutput output = new BinaryOutput(stream)) {
         DumpGame(world, output);
     }
 }
Exemplo n.º 29
0
        public void Encode(BinaryOutput stream)
        {
            stream.Write(World.Name);
            stream.Write(World.Author ?? "");

            World.TilesetContainer.Encode(stream);
            World.EntityContainer.Encode(stream);
            World.EntityTemplateFactory.Encode(stream);
            World.TilesetFactory.Encode(stream);
            World.UIContainer.Encode(stream);
            World.SpriteLibrary.Encode(stream);

            //DFS
            Stack <TreeNode> stack   = new Stack <TreeNode>();
            List <TreeNode>  visited = new List <TreeNode>();

            List <TreeNode> _reversed = lMaps.Nodes[0].Nodes.Cast <TreeNode>().ToList();

            _reversed.Reverse();
            foreach (TreeNode child in _reversed)
            {
                stack.Push(child);
            }

            //OPCODES:
            //0x01 : FOLDER
            //0x02 : FALL-IN
            //0x03 : FALL-BACK
            //0x04 : MAP

            int writeCount = 0;

            Stack <TreeNode> _stack = new Stack <TreeNode>();

            _reversed.Clear();
            _reversed = lMaps.Nodes[0].Nodes.Cast <TreeNode>().ToList();
            _reversed.Reverse();
            foreach (TreeNode child in _reversed)
            {
                _stack.Push(child);
            }

            while (_stack.Count > 0)
            {
                TreeNode node = _stack.Pop();
                writeCount++;
                List <TreeNode> reversed = node.Nodes.Cast <TreeNode>().ToList();
                reversed.Reverse();
                if (reversed.Count > 0)
                {
                    writeCount += 2;
                }
                foreach (TreeNode child in reversed)
                {
                    _stack.Push(child);
                }
            }

            stream.Write(writeCount);

            while (stack.Count > 0)
            {
                TreeNode node = stack.Pop();
                Map      m    = node.Tag as Map;
                visited.Add(node);
                if (m == null)
                {
                    stream.Write(0x01);
                    stream.Write(node.Text);
                    List <TreeNode> reversedChilds = node.Nodes.Cast <TreeNode>().ToList();
                    reversedChilds.Reverse();
                    if (reversedChilds.Count > 0)
                    {
                        stream.Write(0x02);
                    }
                    foreach (TreeNode child in reversedChilds)
                    {
                        stack.Push(child);
                    }
                }
                else
                {
                    stream.Write(0x04);

                    stream.Write(m.Name);
                    stream.Write(m.Author);
                    stream.Write(m.Width);
                    stream.Write(m.Height);

                    /* ENCODE ALL MOCKUP TILESETS */
                    stream.Write(m.Tilesets.Count);
                    foreach (MockupTileset tref in m.Tilesets)
                    {
                        stream.Write(tref.Tileset.Name);
                    }

                    /* ENCODE ALL MOCKUP BEHAVIORS */
                    for (int i = 0; i < m.Width * m.Height; i++)
                    {
                        int x = i % m.Width;
                        int y = i / m.Width;

                        m.Behaviors[x, y].Encode(stream);
                    }

                    /* ENCODE ALL ACTIONS */
                    ActionManager actionmanager = EditorEngine.Instance.GetActionManager(m);
                    ActionIO      writer        = new ActionIO(stream);

                    stream.Write(actionmanager.Actions.Count);
                    foreach (IAction act in actionmanager.Actions)
                    {
                        writer.Write(act);
                    }
                }

                if (node.Parent != null && lMaps.Nodes[0].Nodes[lMaps.Nodes[0].Nodes.Cast <TreeNode>().Count() - 1] != node)
                {
                    bool allDone = true;
                    foreach (TreeNode child in node.Parent.Nodes)
                    {
                        bool done = false;
                        foreach (TreeNode visitedNode in visited.Where(visitedNode => child.Equals(visitedNode)))
                        {
                            done = true;
                        }
                        if (!done)
                        {
                            allDone = false;
                            break;
                        }
                    }
                    if (allDone)
                    {
                        stream.Write(0x03);
                    }
                }
            }
        }
Exemplo n.º 30
0
 public void Encode(BinaryOutput stream)
 {
     stream.Write(this.Rows);
     stream.Write(this.Columns);
     stream.Write(this.Texture);
 }
Exemplo n.º 31
0
 public void Execute(WriteBinaryStateMode mode)
 {
     BinaryOutput?.Write(State, mode);
 }
Exemplo n.º 32
0
        public void Write(NamedVariable t)
        {
            BinaryOutput stream = _stream as BinaryOutput;

            int type = 0;

            if (t is NamedBoolean)
            {
                type = 1;
            }
            else if (t is NamedByte)
            {
                type = 2;
            }
            else if (t is NamedChar)
            {
                type = 3;
            }
            else if (t is NamedDecimal)
            {
                type = 4;
            }
            else if (t is NamedDouble)
            {
                type = 5;
            }
            else if (t is NamedInt16)
            {
                type = 6;
            }
            else if (t is NamedInt32)
            {
                type = 7;
            }
            else if (t is NamedInt64)
            {
                type = 8;
            }
            else if (t is NamedSByte)
            {
                type = 9;
            }
            else if (t is NamedSingle)
            {
                type = 10;
            }
            else if (t is NamedString)
            {
                type = 11;
            }
            else if (t is NamedUInt16)
            {
                type = 12;
            }
            else if (t is NamedUInt32)
            {
                type = 13;
            }
            else if (t is NamedUInt64)
            {
                type = 14;
            }

            stream.Write(type);
            stream.Write(t);
        }
Exemplo n.º 33
0
		public void Encode(BinaryOutput stream) {
			stream.Write((byte) Facing);
			stream.Write((byte) Speed);
		}
Exemplo n.º 34
0
 public void Encode(BinaryOutput stream)
 {
     stream.Write(this.currentId);
 }
Exemplo n.º 35
0
		/// <summary>
		/// Subscribes to information from a set of topics. Topics can include wildcards.
		/// </summary>
		/// <param name="Topics">Topics together with Quality of Service levels for each topic.</param>
		/// <returns>Packet identifier assigned to subscription.</returns>
		public ushort SUBSCRIBE(params KeyValuePair<string, MqttQualityOfService>[] Topics)
		{
			BinaryOutput Payload = new BinaryOutput();
			ushort PacketIdentifier;

			PacketIdentifier = this.packetIdentifier++;
			if (PacketIdentifier == 0)
				PacketIdentifier = this.packetIdentifier++;

			Payload.WriteUInt16(PacketIdentifier);

			foreach (KeyValuePair<string, MqttQualityOfService> Pair in Topics)
			{
				Payload.WriteString(Pair.Key);
				Payload.WriteByte((byte)Pair.Value);
			}

			byte[] PayloadData = Payload.GetPacket();

			BinaryOutput Packet = new BinaryOutput();
			byte b = (byte)((int)MqttControlPacketType.SUBSCRIBE << 4);
			b |= 2;

			Packet.WriteByte(b);
			Packet.WriteUInt((uint)PayloadData.Length);
			Packet.WriteBytes(PayloadData);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, PacketIdentifier);

			return PacketIdentifier;
		}
Exemplo n.º 36
0
		private void DISCONNECT()
		{
			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)MqttControlPacketType.DISCONNECT << 4);
			Packet.WriteUInt(2);

			byte[] PacketData = Packet.GetPacket();

			ManualResetEvent Done = new ManualResetEvent(false);

			this.stream.BeginWrite(PacketData, 0, PacketData.Length, this.EndDisconnect, Done);

			Done.WaitOne(1000);
		}
Exemplo n.º 37
0
		/// <summary>
		/// Sends a PING message to the server. This is automatically done to keep the connection alive. Only call this method
		/// if you want to send additional PING messages, apart from the ones sent to keep the connection alive.
		/// </summary>
		public void PING()
		{
			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)MqttControlPacketType.PINGREQ << 4);
			Packet.WriteUInt(0);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, 0);

			EventHandler h = this.OnPing;
			if (h != null)
			{
				try
				{
					h(this, new EventArgs());
				}
				catch (Exception ex)
				{
#if LineListener
					LLOut(ex.Message, Color.Yellow, Color.DarkRed);
#endif
				}
			}
		}
Exemplo n.º 38
0
 public void Encode(BinaryOutput stream)
 {
     stream.Write((byte)Facing);
     stream.Write((byte)Speed);
 }
Exemplo n.º 39
0
		/// <summary>
		/// Publishes information on a topic.
		/// </summary>
		/// <param name="Topic">Topic name</param>
		/// <param name="QoS">Quality of service</param>
		/// <param name="Retain">If topic shoudl retain information.</param>
		/// <param name="Data">Binary data to send.</param>
		/// <returns>Packet identifier assigned to data.</returns>
		public int PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, BinaryOutput Data)
		{
			return this.PUBLISH(Topic, QoS, Retain, false, Data.GetPacket());
		}
Exemplo n.º 40
0
        public static void Main(string[] args)
        {
            Initialize();

            try
            {
                DateTime Start    = DateTime.Now;
                Guid     PlayerId = Guid.NewGuid();
                string   Name;

                Console.Out.WriteLine("Hello. What is your name?");
                Name = Console.ReadLine();

                using (MultiPlayerEnvironment MPE = new MultiPlayerEnvironment("MultiPlayerSetup", true,
                                                                               "iot.eclipse.org", 1883, false, string.Empty, string.Empty, "RetroSharp/Examples/Networking/MultiPlayerSetup",
                                                                               5, PlayerId, new KeyValuePair <string, string>("NAME", Name)))
                {
                    MPE.OnStateChange += (sender, newstate) => Console.Out.WriteLine(newstate.ToString());

                    MPE.OnPlayerAvailable += (sender, player) =>
                    {
                        Console.Out.WriteLine("New player available: " + player["NAME"]);
                        if (sender.PlayerCount >= 5 || (DateTime.Now - Start).TotalSeconds >= 20)
                        {
                            MPE.ConnectPlayers();
                        }
                    };

                    MPE.OnPlayerConnected += (sender, player) => Console.Out.WriteLine("Player connected: " + player["NAME"]);

                    MPE.OnGameDataReceived += (sender, e) => Console.Out.WriteLine(e.FromPlayer["NAME"] + ": " + e.Data.ReadString());

                    MPE.OnPlayerDisconnected += (sender, player) => Console.Out.WriteLine("Player disconnected: " + player["NAME"]);

                    if (!MPE.Wait(20000))
                    {
                        if (MPE.State == MultiPlayerState.FindingPlayers)
                        {
                            MPE.ConnectPlayers();
                        }
                        else
                        {
                            throw new Exception("Unable to setup multi-player environment.");
                        }
                    }

                    Console.Out.WriteLine(MPE.PlayerCount.ToString() + " player(s) now connected.");
                    Console.Out.WriteLine("Write anything and send it to the others.");
                    Console.Out.WriteLine("An empty row will quit the application.");
                    Console.Out.WriteLine();

                    string s = Console.In.ReadLine();

                    while (!string.IsNullOrEmpty(s))
                    {
                        BinaryOutput Msg = new BinaryOutput();
                        Msg.WriteString(s);
                        MPE.SendTcpToAll(Msg.GetPacket());

                        s = Console.In.ReadLine();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                Console.In.ReadLine();
            }

            Terminate();
        }
Exemplo n.º 41
0
		private void PUBREL(ushort PacketIdentifier)
		{
			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)(((int)MqttControlPacketType.PUBREL << 4) | 2));
			Packet.WriteUInt(2);
			Packet.WriteUInt16(PacketIdentifier);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, PacketIdentifier);
		}
Exemplo n.º 42
0
		public void Encode(BinaryOutput stream) {
			stream.Write(Uid);
			stream.Write(Elapsed);
			stream.Write(Duration);
		}
Exemplo n.º 43
0
        public static void Main(string[] args)
        {
            Initialize();

            WriteLine("What is your name?", C64Colors.LightBlue);
            string       Name = Console.In.ReadLine();
            BinaryOutput Payload;

            WriteLine("Hello " + Name + ".", C64Colors.LightBlue);
            WriteLine("Strings entered below will be seen by everybody running the application.", C64Colors.LightBlue);
            WriteLine("Enter an empty string to close the application.", C64Colors.LightBlue);
            WriteLine(new string('-', ConsoleWidth), C64Colors.LightBlue);

            using (MqttConnection MqttConnection = ConnectToMqttServer("iot.eclipse.org", true, 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/MultiUserChat");

                        Payload = new BinaryOutput();
                        Payload.WriteString(MqttConnection.ClientId);
                        Payload.WriteString(Name);
                        Payload.WriteByte(0);

                        MqttConnection.PUBLISH("RetroSharp/Examples/Networking/MultiUserChat", MqttQualityOfService.AtLeastOne, false, Payload);
                    }
                };

                MqttConnection.OnContentReceived += (sender, Content) =>
                {
                    string ClientId = Content.DataInput.ReadString();
                    if (ClientId != sender.ClientId)
                    {
                        string Author  = Content.DataInput.ReadString();
                        byte   Command = Content.DataInput.ReadByte();

                        switch (Command)
                        {
                        case 0:
                            WriteLine("<" + Author + " enters the room.>", C64Colors.LightGreen);
                            break;

                        case 1:
                            string Text = Content.DataInput.ReadString();
                            WriteLine(Author + ": " + Text, C64Colors.LightBlue);
                            break;

                        case 2:
                            WriteLine("<" + Author + " left the room.>", C64Colors.LightGreen);
                            break;
                        }
                    }
                };

                while (true)
                {
                    string s = Console.In.ReadLine();
                    if (string.IsNullOrEmpty(s))
                    {
                        break;
                    }

                    Payload = new BinaryOutput();
                    Payload.WriteString(MqttConnection.ClientId);
                    Payload.WriteString(Name);
                    Payload.WriteByte(1);
                    Payload.WriteString(s);

                    MqttConnection.PUBLISH("RetroSharp/Examples/Networking/MultiUserChat", MqttQualityOfService.AtLeastOne, false, Payload);
                }

                MqttConnection.UNSUBSCRIBE("RetroSharp/Examples/Networking/MultiUserChat");

                int PacketIdentifier        = 0;
                ManualResetEvent Terminated = new ManualResetEvent(false);

                MqttConnection.OnPublished += (sender, e) =>
                {
                    if (PacketIdentifier == e)
                    {
                        Terminated.Set();
                    }
                };

                Payload = new BinaryOutput();
                Payload.WriteString(MqttConnection.ClientId);
                Payload.WriteString(Name);
                Payload.WriteByte(2);

                PacketIdentifier = MqttConnection.PUBLISH("RetroSharp/Examples/Networking/MultiUserChat", MqttQualityOfService.AtLeastOne, false, Payload);

                Terminated.WaitOne(5000);
            }

            Terminate();
        }
Exemplo n.º 44
0
		/// <summary>
		/// Unsubscribes from information earlier subscribed to. Topics can include wildcards.
		/// </summary>
		/// <param name="Topics">Topics</param>
		/// <returns>Packet identifier assigned to unsubscription.</returns>
		public ushort UNSUBSCRIBE(params string[] Topics)
		{
			BinaryOutput Payload = new BinaryOutput();
			ushort PacketIdentifier;

			PacketIdentifier = this.packetIdentifier++;
			if (PacketIdentifier == 0)
				PacketIdentifier = this.packetIdentifier++;

			Payload.WriteUInt16(PacketIdentifier);

			foreach (string Topic in Topics)
				Payload.WriteString(Topic);

			byte[] PayloadData = Payload.GetPacket();

			BinaryOutput Packet = new BinaryOutput();
			byte b = (byte)((int)MqttControlPacketType.UNSUBSCRIBE << 4);
			b |= 2;

			Packet.WriteByte(b);
			Packet.WriteUInt((uint)PayloadData.Length);
			Packet.WriteBytes(PayloadData);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, PacketIdentifier);

			return PacketIdentifier;
		}
Exemplo n.º 45
0
 public void Serialize(BinaryOutput output)
 {
     output.Write(ConquerDirectory);
     output.Write(Effects);
 }
Exemplo n.º 46
0
		private void CONNECT(int KeepAliveSeconds)
		{
			this.State = MqttState.Authenticating;
			this.keepAliveSeconds = KeepAliveSeconds;
			this.nextPing = DateTime.Now.AddMilliseconds(KeepAliveSeconds * 500);
			this.secondTimer = new Timer(this.secondTimer_Elapsed, null, 1000, 1000);

			BinaryOutput Payload = new BinaryOutput();
			Payload.WriteString("MQTT");
			Payload.WriteByte(4);	// v3.1.1

			byte b = 2;		// Clean session.

			Payload.WriteByte(b);

			Payload.WriteByte((byte)(KeepAliveSeconds >> 8));
			Payload.WriteByte((byte)KeepAliveSeconds);

			Payload.WriteString(this.clientId);
			if (!string.IsNullOrEmpty(this.userName))
			{
				b |= 128;
				Payload.WriteString(this.userName);

				if (!string.IsNullOrEmpty(this.password))
				{
					b |= 64;
					Payload.WriteString(this.password);
				}
			}

			byte[] PayloadData = Payload.GetPacket();

			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)MqttControlPacketType.CONNECT << 4);
			Packet.WriteUInt((uint)PayloadData.Length);
			Packet.WriteBytes(PayloadData);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, 0);
			this.inputState = 0;
			this.BeginRead();
		}
Exemplo n.º 47
0
 public void Encode(BinaryOutput stream)
 {
     //don't do jackshit, we need a World!
 }
Exemplo n.º 48
0
		private void PINGRESP()
		{
			BinaryOutput Packet = new BinaryOutput();
			Packet.WriteByte((byte)MqttControlPacketType.PINGRESP << 4);
			Packet.WriteUInt(0);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, 0);
		}
Exemplo n.º 49
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);
                }
            }
        }
Exemplo n.º 50
0
		private ushort PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, bool Duplicate, byte[] Data)
		{
			BinaryOutput Payload = new BinaryOutput();
			ushort PacketIdentifier;

			Payload.WriteString(Topic);

			if (QoS > MqttQualityOfService.AtMostOne)
			{
				PacketIdentifier = this.packetIdentifier++;
				if (PacketIdentifier == 0)
					PacketIdentifier = this.packetIdentifier++;

				Payload.WriteUInt16(PacketIdentifier);
			}
			else
				PacketIdentifier = 0;

			Payload.WriteBytes(Data);

			byte[] PayloadData = Payload.GetPacket();

			BinaryOutput Packet = new BinaryOutput();
			byte b = (byte)((int)MqttControlPacketType.PUBLISH << 4);
			if (Duplicate)
				b |= 8;

			b |= (byte)((int)QoS << 1);

			if (Retain)
				b |= 1;

			Packet.WriteByte(b);
			Packet.WriteUInt((uint)PayloadData.Length);
			Packet.WriteBytes(PayloadData);

			byte[] PacketData = Packet.GetPacket();

			this.BeginWrite(PacketData, PacketIdentifier);

			return PacketIdentifier;
		}
Exemplo n.º 51
0
 public LZW(string inputFileName, string outputFileName)
 {
     input  = new BinaryInput(inputFileName);
     output = new BinaryOutput(outputFileName);
 }
Exemplo n.º 52
0
		public void Encode(BinaryOutput stream) {
			stream.Write(BehaviorId);
		}
Exemplo n.º 53
0
 public void Encode(BinaryOutput stream)
 {
     stream.Write(BehaviorId);
 }
Exemplo n.º 54
0
        public void GetGift(int PlayerIndex, int GiftIndex, BinaryOutput Output, BinaryInput Input)
        {
            switch (GiftIndex)
            {
            case 0:
                this.framesPerPixel = 4;
                this.stepsPerFrame  = 1;
                Program.PlayerMsg(this.playerNr, "Slow speed");
                break;

            case 1:
                this.framesPerPixel = 5;
                this.stepsPerFrame  = 1;
                Program.PlayerMsg(this.playerNr, "Slower speed");
                break;

            case 2:
                this.framesPerPixel = 6;
                this.stepsPerFrame  = 1;
                Program.PlayerMsg(this.playerNr, "Slowest speed");
                break;

            case 3:
                this.framesPerPixel = 2;
                this.stepsPerFrame  = 1;
                Program.PlayerMsg(this.playerNr, "Fast speed");
                break;

            case 4:
                this.framesPerPixel = 1;
                this.stepsPerFrame  = 1;
                Program.PlayerMsg(this.playerNr, "Faster speed");
                break;

            case 5:
                this.framesPerPixel = 1;
                this.stepsPerFrame  = 2;
                if (this.shotSpeed < 2)
                {
                    this.shotSpeed = 2;
                }
                Program.PlayerMsg(this.playerNr, "Fastest speed");
                break;

            case 6:
                this.framesPerPixel = 3;
                this.stepsPerFrame  = 1;
                Program.PlayerMsg(this.playerNr, "Normal speed");
                break;

            case 7:
                this.shotPower = 5;
                Program.PlayerMsg(this.playerNr, "Tiny bullets");
                break;

            case 8:
                this.shotPower = 10;
                Program.PlayerMsg(this.playerNr, "Small bullets");
                break;

            case 9:
                this.shotPower = 15;
                Program.PlayerMsg(this.playerNr, "Normal bullets");
                break;

            case 10:
                this.shotPower = 20;
                Program.PlayerMsg(this.playerNr, "Large bullets");
                break;

            case 11:
                this.shotPower = 25;
                Program.PlayerMsg(this.playerNr, "Huge bullets");
                break;

            case 12:
                this.shotPower = 30;
                Program.PlayerMsg(this.playerNr, "Humongous bullets");
                break;

            case 13:
                this.shotPower = 50;
                Program.PlayerMsg(this.playerNr, "Peace-maker bullets");
                break;

            case 14:
                this.tail = false;
                Program.PlayerMsg(this.playerNr, "No tail");
                break;

            case 15:
                this.tail = true;
                Program.PlayerMsg(this.playerNr, "Tail");
                break;

            case 16:
                this.shotSpeed = Math.Max(1, this.stepsPerFrame);
                Program.PlayerMsg(this.playerNr, "Slow bullets");
                break;

            case 17:
                this.shotSpeed = Math.Max(2, this.stepsPerFrame);
                Program.PlayerMsg(this.playerNr, "Fast bullets");
                break;

            case 18:
                this.shotSpeed = Math.Max(3, this.stepsPerFrame);
                Program.PlayerMsg(this.playerNr, "Faster bullets");
                break;

            case 19:
                this.shotSpeed = Math.Max(4, this.stepsPerFrame);
                Program.PlayerMsg(this.playerNr, "Fastest bullets");
                break;

            case 20:
                int  X, Y;
                int  dx, dy;
                bool Ok;
                int  TriesLeft = 100;
                int  Black     = Color.Black.ToArgb();

                if (!(Input is null))
                {
                    this.x = 319 - (int)Input.ReadInt();
                    this.y = 207 - (int)Input.ReadInt();
                }
                else
                {
                    Ok = false;

                    while (TriesLeft-- > 0 && !Ok)
                    {
                        X  = RetroApplication.Random(30, 290);
                        Y  = RetroApplication.Random(38, 170);
                        Ok = true;
                        for (dy = -5; dy < 5; dy++)
                        {
                            for (dx = -5; dx < 5; dx++)
                            {
                                if (RetroApplication.Raster[X + dx, Y + dy].ToArgb() != Black)
                                {
                                    Ok = false;
                                    dy = 5;
                                    break;
                                }
                            }
                        }

                        if (Ok)
                        {
                            Output.WriteInt(X);
                            Output.WriteInt(Y);

                            this.x = X;
                            this.y = Y;
                        }
                    }

                    if (!Ok && !(Output is null))
                    {
                        Output.WriteInt(this.x);
                        Output.WriteInt(this.y);
                    }
                }

                Program.PlayerMsg(this.playerNr, "Teleport");
                break;
Exemplo n.º 55
0
 public void Encode(BinaryOutput stream)
 {
 }
Exemplo n.º 56
0
 public override void Encode(BinaryOutput stream)
 {
     base.Encode(stream);
     stream.Write(value);
 }
Exemplo n.º 57
0
        /*****************************************************************************************************/
        static void InitDeviceObjects()
        {
            // create the device object with StructuredView acceptation
            device = new DeviceObject(deviceId, "Device test", "A test Device", true);

            // ANALOG_INPUT:0 double
            // initial value 0
            // Take care all ANALOG_INPUT, ANALOG_OUTPUT, ANALOG_VALUE must be float or double not int !
            // to comply with the standard
            ana0 = new AnalogInput <double>
                   (
                0,
                "Ana0 Sin double",
                "Ana0 Sin double",
                0,
                BacnetUnitsId.UNITS_AMPERES
                   );
            ana0.m_PROP_HIGH_LIMIT = 50;
            ana0.m_PROP_LOW_LIMIT  = -50;
            ana0.m_PROP_DEADBAND   = 5;
            ana0.Enable_Reporting(true, 0);

            device.AddBacnetObject(ana0);   // don't forget to do this

            // Binary Output
            BinaryOutput bo = new BinaryOutput(0, "Bin Out", "An output", false);

            bo.m_PROP_MINIMUM_ON_TIME = bo.m_PROP_MINIMUM_OFF_TIME = 30; // 30s Minumum states time
            device.AddBacnetObject(bo);

            // Create A StructuredView
            StructuredView s = new StructuredView(0, "Content", "A View");

            // register it
            device.AddBacnetObject(s);  // don't forget to do this

            BaCSharpObject b;

            // ANALOG_VALUE:0 double with Priority Array
            //
            b = new AnalogValue <double>
                (
                0,
                "Ana0 Double",
                "Ana0 Double",
                5465.23,
                BacnetUnitsId.UNITS_BARS,
                true
                );
            s.AddBacnetObject(b); // Put it in the view

            b.OnWriteNotify += new BaCSharpObject.WriteNotificationCallbackHandler(handler_OnWriteNotify);

            // ANALOG_OUTPUT:1 float with Priority Array on Present Value
            b = new AnalogOutput <float>
                (
                1,
                "Ana1 float",
                "Ana1 float",
                (int)56,
                BacnetUnitsId.UNITS_DEGREES_CELSIUS
                );
            s.AddBacnetObject(b); // Put it in the view

            b.OnWriteNotify += new BaCSharpObject.WriteNotificationCallbackHandler(handler_OnWriteNotify);

            // MULTI_STATE_OUTPUT:4 with 6 states
            MultiStateOutput m = new MultiStateOutput
                                 (
                4,
                "MultiStates",
                "MultiStates",
                1,
                6
                                 );

            for (int i = 1; i < 7; i++)
            {
                m.m_PROP_STATE_TEXT[i - 1] = new BacnetValue("Text Level " + i.ToString());
            }

            s.AddBacnetObject(m); // in the view

            StructuredView s2 = new StructuredView(1, "Complex objects", "Complex objects");

            s.AddBacnetObject(s2);

            // TREND_LOG:0 with int values
            // new TrendLog can be changed by new TrendLogCustom
            trend0 = new TrendLog(0, "Trend signed int", "Trend signed int", 200, BacnetTrendLogValueType.TL_TYPE_SIGN);
            s2.AddBacnetObject(trend0); // in the second level view
            // fill Log with more values than the size
            for (int i = 0; i < 300; i++)
            {
                DateTime current = DateTime.Now.AddSeconds(-300 + i);
                if ((i > 200) && (i < 210))   // simulate some errors in the trend
                {
                    trend0.AddValue(new BacnetError(), current, 0, BacnetTrendLogValueType.TL_TYPE_ERROR);
                }
                else
                {
                    trend0.AddValue((int)(i * Math.Sin((float)i / 0.01)), current, 0);
                }
            }

            trend0.AddValue(new BacnetError(), DateTime.Now, 0, BacnetTrendLogValueType.TL_TYPE_ERROR);

            // BACFILE:0
            // File access right me be allowed to the current user
            // for read and for write if any
            b = new BacnetFile
                (
                0,
                "A file",
                "File description",
                "c:\\RemoteObject.xml",
                false
                );
            s2.AddBacnetObject(b); // in the second level view

            NotificationClass nc = new NotificationClass
                                   (
                0,
                "An alarm sender",
                "Alarm description"
                                   );

            device.AddBacnetObject(nc);

            // Put two elements into the NC recipient List

            // Valid Day
            BacnetBitString week = new BacnetBitString();

            for (int i = 0; i < 7; i++)
            {
                week.SetBit((byte)i, true);                         // Monday to Sunday
            }
            // transition
            BacnetBitString transition = new BacnetBitString();

            transition.SetBit(0, true); // To OffNormal
            transition.SetBit(1, true); // To Fault
            transition.SetBit(2, true); // To Normal

            DeviceReportingRecipient r = new DeviceReportingRecipient
                                         (
                week,                          // week days
                DateTime.MinValue.AddDays(10), // fromTime
                DateTime.MaxValue,             // toTime
                new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, 4000),
                (uint)4,                       // processid
                true,                          // Ack required
                transition                     // transition
                                         );

            nc.AddReportingRecipient(r);

            r = new DeviceReportingRecipient
                (
                week,
                DateTime.MinValue.AddDays(10),
                DateTime.MaxValue,
                new BacnetAddress(BacnetAddressTypes.IP, 0, new Byte[6] {
                255, 255, 255, 255, 0xBA, 0xC0
            }),
                (uint)4,
                true,
                transition
                );

            nc.AddReportingRecipient(r);

            // Create a Schedule
            Schedule sch = new Schedule(0, "Schedule", "Schedule");

            // MUST be added to the device list before modification
            device.AddBacnetObject(sch);

            // a link to the internal analog output
            sch.AddPropertyReference(new BacnetDeviceObjectPropertyReference
                                     (
                                         new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_OUTPUT, 1),
                                         BacnetPropertyIds.PROP_PRESENT_VALUE)
                                     );
            // a link to analog output through the network : could be on another device than itself
            sch.AddPropertyReference(new BacnetDeviceObjectPropertyReference
                                     (
                                         new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_OUTPUT, 1),
                                         BacnetPropertyIds.PROP_PRESENT_VALUE,
                                         new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, 4000))
                                     );

            sch.PROP_SCHEDULE_DEFAULT = (int)452;

            // Schedule a change today in 60 seconds
            sch.AddSchedule
            (
                DateTime.Now.DayOfWeek == 0 ? 6 : (int)DateTime.Now.DayOfWeek - 1, // Monday=0, Sunday=6
                DateTime.Now.AddSeconds(10), (int)900
            );
            sch.PROP_OUT_OF_SERVICE = false;    // needed after all initialization to start the service

            // One empty Calendar, could be fullfill with yabe

            Calendar cal = new Calendar(0, "Test Calendar", "A Yabe calendar");

            device.AddBacnetObject(cal);
        }