Example #1
0
 void Start()
 {
     game = GameObject.Find("Networking").GetComponent<Game>();
     sender = GameObject.Find("Networking").GetComponent<PacketSender>();
     chat = GameObject.Find("Chat").GetComponent<Chat>();
     side = GameObject.Find("SideObjects").GetComponent<SideObjects>();
 }
Example #2
0
		public PacketParser(PacketIn packet, PacketSender sender, PacketDefinition def)
		{
			if (packet.PacketId == RealmServerOpCode.SMSG_COMPRESSED_MOVES)
			{
				var packet2 = ParseCompressedMove(packet);
				if (packet2 != null)
				{
					packet = packet2;
				}
			}
			Packet = packet;
			Sender = sender;
			Definition = def;
			Timestamp = DateTime.Now;
		}
Example #3
0
	public override IEnumerator SetupAsync ()
	{
		netInterface = new NetworkInterface();
		packetSender = new PacketSender();
		packetReceiver = new PacketReceiver(netInterface);
		packetReceiver.AddPacketListener(OnReceivePacket);

		netInterface.ConnectTo(ip, port);

		while (netInterface.State == ConnectionState.Connecting)
		{
			yield return null;
		}

		Debug.Log("Connected!");

		// var data = System.Text.Encoding.ASCII.GetBytes("hello~");

		// netInterface.Send(data);
		netInterface.StartReceive();
	}
Example #4
0
 void Start()
 {
     game   = GameObject.Find("Networking").GetComponent <Game>();
     sender = GameObject.Find("Networking").GetComponent <PacketSender>();
 }
Example #5
0
        public Status(Entity en, SpellBase spell, StatusTypes type, int duration, string data)
        {
            mEntity   = en;
            Spell     = spell;
            Type      = type;
            StartTime = Globals.Timing.TimeMs;
            Duration  = Globals.Timing.TimeMs + duration;
            Data      = data;

            if (en.GetType() == typeof(Player))
            {
                if (type == StatusTypes.Blind ||
                    type == StatusTypes.Silence ||
                    type == StatusTypes.Sleep ||
                    type == StatusTypes.Snare ||
                    type == StatusTypes.Stun ||
                    type == StatusTypes.Taunt)
                {
                    Duration = Globals.Timing.TimeMs + duration - (long)(((Player)en).GetTenacity() / 100 * duration);
                }
            }

            if (type == StatusTypes.Shield)
            {
                for (var i = (int)Vitals.Health; i < (int)Vitals.VitalCount; i++)
                {
                    shield[i] = Math.Abs(spell.Combat.VitalDiff[i]) +
                                (int)(spell.Combat.Scaling * en.Stat[spell.Combat.ScalingStat].BaseStat / 100f);
                }
            }

            //If new Cleanse spell, remove all over status effects.
            if (Type == StatusTypes.Cleanse)
            {
                en.Statuses.Clear();
            }
            else
            {
                //If user has a cleanse on, don't add status
                var statuses = en.Statuses.Values.ToArray();
                foreach (var status in statuses)
                {
                    if (status.Type == StatusTypes.Cleanse)
                    {
                        PacketSender.SendActionMsg(en, Strings.Combat.status[(int)Type], CustomColors.Combat.Cleanse);

                        return;
                    }
                }
            }

            if (en.Statuses.ContainsKey(spell))
            {
                en.Statuses[spell].Duration  = Duration;
                en.Statuses[spell].StartTime = StartTime;
            }
            else
            {
                en.Statuses.Add(Spell, this);
            }

            PacketSender.SendEntityVitals(mEntity);
        }
Example #6
0
		/// <summary>
		/// Dumps the content of an Update packet to the console
		/// </summary>
		//public static void DumpUpdatePacket(RealmPacketOut packet)
		//{
		//    try
		//    {
		//        ParsedUpdatePacket.Dump(packet.GetPacketPayload(), false, m_updatePacketWriter);
		//        m_updatePacketWriter.Flush();
		//    }
		//    catch (Exception e)
		//    {
		//        OnException("Failed to parse Update-Packet.", e, packet.GetPacketPayload());
		//    }
		//}

		public static void DumpPacketOut(RealmAccount acc, byte[] packetOut, int offset, int length, PacketSender sender)
		{
			if (Dumps)
			{
				var writer = GetTextWriter(acc);
				using (var packet = DisposableRealmPacketIn.CreateFromOutPacket(packetOut, offset, length))
				{
					if (CanDump(packet.PacketId))
					{
						DumpPacket(packet, sender, false, writer);
					}
				}
			}
		}
Example #7
0
		static void AddRealmPacket(IDictionary<RealmServerOpCode, LockfreeQueue<RealmReceiveInfo>> packets,
			PacketSender sender, PacketIn packet, TestFakeClient client)
		{
			var opCode = (RealmServerOpCode)packet.PacketId.RawId;

			LockfreeQueue<RealmReceiveInfo> queue;
			if (!packets.TryGetValue(opCode, out queue))
			{
				packets.Add(opCode, queue = new LockfreeQueue<RealmReceiveInfo>());
			}

			var def = PacketAnalyzer.GetDefinition(packet.PacketId, sender);
			if (def != null)
			{
				if (packet is RealmPacketIn)
				{
					packet = ((DisposableRealmPacketIn) packet).Copy();
				}
				var parser = new PacketParser(packet, sender);
				parser.Parse();
				queue.Enqueue(new RealmReceiveInfo { Parser = parser, Client = client });

				//packet.IncrementUsage();
			}
		}
Example #8
0
 public Building(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #9
0
 protected override bool Invoke(IPacketHandler handler, PacketSender packetSender, IPacket packet) =>
 handler.Handle(packetSender, packet);
Example #10
0
 void _addSpeedBtn_Clicked(Base sender, ClickedEventArgs arguments)
 {
     PacketSender.SendUpgradeStat((int)Stats.Speed);
 }
Example #11
0
 public PacketDefinition(PacketId[] packetIds, PacketSender sender, params PacketSegmentStructure[] structure)
     : this(packetIds, sender, new ComplexPacketSegmentStructure(structure))
 {
 }
Example #12
0
		public ParsablePacketInfo(PacketIn packet, PacketSender sender, DateTime timestamp)
		{
			Packet = packet;
			Sender = sender;
			Timestamp = timestamp;
		}
Example #13
0
 void Start()
 {
     game = GameObject.Find("Networking").GetComponent<Game>();
     sender = GameObject.Find("Networking").GetComponent<PacketSender>();
 }
Example #14
0
		public PacketParser(PacketIn packet, PacketSender sender)
			: this(packet, sender, PacketAnalyzer.GetDefinition(packet.PacketId, sender))
		{

		}
Example #15
0
		public static ParsedSegment Parse(RealmPacketOut realmPacketOut, PacketSender sender, PacketDefinition def)
		{
			using (var packetIn = DisposableRealmPacketIn.CreateFromOutPacket(realmPacketOut))
			{
				//if (packetIn.PacketID == RealmServerOpCode.SMSG_COMPRESSED_MOVE)
				//{
				//    using (var movePacket = ParseCompressedMove(packetIn))
				//    {
				//        return Parse(movePacket, sender, def);
				//    }
				//}
				return Parse(packetIn, sender, def);
			}
		}
Example #16
0
		public static ParsedSegment Parse(RealmPacketOut realmPacketOut, PacketSender sender)
		{
			return Parse(realmPacketOut, sender, PacketAnalyzer.GetDefinition(realmPacketOut.PacketId, sender));
		}
Example #17
0
        public void Update()
        {
            if (Globals.Bag[mMySlot].ItemId != mCurrentItemId)
            {
                mCurrentItemId = Globals.Bag[mMySlot].ItemId;
                var item = ItemBase.Get(Globals.Bag[mMySlot].ItemId);
                if (item != null)
                {
                    var itemTex = Globals.ContentManager.GetTexture(GameContentManager.TextureType.Item, item.Icon);
                    if (itemTex != null)
                    {
                        Pnl.Texture = itemTex;
                    }
                    else
                    {
                        if (Pnl.Texture != null)
                        {
                            Pnl.Texture = null;
                        }
                    }
                }
                else
                {
                    if (Pnl.Texture != null)
                    {
                        Pnl.Texture = null;
                    }
                }
            }

            if (!IsDragging)
            {
                if (mMouseOver)
                {
                    if (!Globals.InputManager.MouseButtonDown(GameInput.MouseButtons.Left))
                    {
                        mCanDrag = true;
                        mMouseX  = -1;
                        mMouseY  = -1;
                        if (Globals.System.GetTimeMs() < mClickTime)
                        {
                            //Globals.Me.TryUseItem(_mySlot);
                            mClickTime = 0;
                        }
                    }
                    else
                    {
                        if (mCanDrag && Draggable.Active == null)
                        {
                            if (mMouseX == -1 || mMouseY == -1)
                            {
                                mMouseX = InputHandler.MousePosition.X - Pnl.LocalPosToCanvas(new Point(0, 0)).X;
                                mMouseY = InputHandler.MousePosition.Y - Pnl.LocalPosToCanvas(new Point(0, 0)).Y;
                            }
                            else
                            {
                                var xdiff = mMouseX -
                                            (InputHandler.MousePosition.X - Pnl.LocalPosToCanvas(new Point(0, 0)).X);

                                var ydiff = mMouseY -
                                            (InputHandler.MousePosition.Y - Pnl.LocalPosToCanvas(new Point(0, 0)).Y);

                                if (Math.Sqrt(Math.Pow(xdiff, 2) + Math.Pow(ydiff, 2)) > 5)
                                {
                                    IsDragging = true;
                                    mDragIcon  = new Draggable(
                                        Pnl.LocalPosToCanvas(new Point(0, 0)).X + mMouseX,
                                        Pnl.LocalPosToCanvas(new Point(0, 0)).X + mMouseY, Pnl.Texture
                                        );
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (mDragIcon.Update())
                {
                    //Drug the item and now we stopped
                    IsDragging = false;
                    var dragRect = new FloatRect(
                        mDragIcon.X - sItemXPadding / 2, mDragIcon.Y - sItemYPadding / 2, sItemXPadding / 2 + 32,
                        sItemYPadding / 2 + 32
                        );

                    float bestIntersect      = 0;
                    var   bestIntersectIndex = -1;

                    //So we picked up an item and then dropped it. Lets see where we dropped it to.
                    //Check inventory first.
                    if (mBagWindow.RenderBounds().IntersectsWith(dragRect))
                    {
                        for (var i = 0; i < Globals.Bag.Length; i++)
                        {
                            if (mBagWindow.Items[i].RenderBounds().IntersectsWith(dragRect))
                            {
                                if (FloatRect.Intersect(mBagWindow.Items[i].RenderBounds(), dragRect).Width *
                                    FloatRect.Intersect(mBagWindow.Items[i].RenderBounds(), dragRect).Height >
                                    bestIntersect)
                                {
                                    bestIntersect =
                                        FloatRect.Intersect(mBagWindow.Items[i].RenderBounds(), dragRect).Width *
                                        FloatRect.Intersect(mBagWindow.Items[i].RenderBounds(), dragRect).Height;

                                    bestIntersectIndex = i;
                                }
                            }
                        }

                        if (bestIntersectIndex > -1)
                        {
                            if (mMySlot != bestIntersectIndex)
                            {
                                //Try to swap....
                                PacketSender.SendMoveBagItems(bestIntersectIndex, mMySlot);
                            }
                        }
                    }

                    mDragIcon.Dispose();
                }
            }
        }
Example #18
0
 void _addDefenseBtn_Clicked(Base sender, ClickedEventArgs arguments)
 {
     PacketSender.SendUpgradeStat((int)Stats.Defense);
 }
Example #19
0
 public CyclopsActivateShieldProcessor(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #20
0
 void _addAttackBtn_Clicked(Base sender, ClickedEventArgs arguments)
 {
     PacketSender.SendUpgradeStat((int)Stats.Attack);
 }
Example #21
0
		public static ParsedSegment Parse(PacketIn packet, PacketSender sender, PacketDefinition def)
		{
			var parser = new PacketParser(packet, sender, def);
			parser.Parse();
			return parser.ParsedPacket;
		}
Example #22
0
 public void Destroy(int dropitems = 0, Entity killer = null)
 {
     Die(dropitems, killer);
     PacketSender.SendEntityDie(this);
     PacketSender.SendEntityLeave(this);
 }
 public ConstructionAmountChangedProcessor(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #24
0
 public BroadcastEscapePodsProcessor(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #25
0
 private void toolStripItemNew_Click(object sender, EventArgs e)
 {
     PacketSender.SendCreateObject(GameObjectType.Crafts);
 }
Example #26
0
 public static bool IsDefined(PacketId packetId, PacketSender sender)
 {
     return GetDefinition(PacketDefinitions[(uint)packetId.Service], packetId.RawId, sender) != null;
 }
Example #27
0
		public static void DumpPacket(RealmAccount acc, RealmPacketIn packet, bool copy, PacketSender sender)
		{
			if (CanDump(packet.PacketId))
			{
				var writer = GetTextWriter(acc);
				DumpPacket(packet, sender, copy, writer);
			}
		}
Example #28
0
 static PacketDefinition GetDefinition(PacketDefinition[] arr, uint rawId, PacketSender sender)
 {
     #if DEBUG
     if (rawId * 2 >= arr.Length)
     {
         //Debugger.Break();
         log.Error("Invalid Packet definition: " + rawId);
         return arr[0];
     }
     #endif
     if (sender == PacketSender.Any || sender == PacketSender.Client)
     {
         return arr[rawId * 2];
     }
     return arr[rawId * 2 + 1];
 }
Example #29
0
        public void Update(long timeMs)
        {
            var sendLeave            = false;
            var originalPageInstance = PageInstance;

            if (PageInstance != null)
            {
                //Check for despawn
                if (PageInstance.ShouldDespawn())
                {
                    X            = PageInstance.X;
                    Y            = PageInstance.Y;
                    PageInstance = null;
                    CallStack.Clear();
                    PlayerHasDied = false;
                    if (HoldingPlayer)
                    {
                        PacketSender.SendReleasePlayer(Player, Id);
                        HoldingPlayer = false;
                    }

                    sendLeave = true;
                }
                else
                {
                    if (!Global)
                    {
                        PageInstance.Update(
                            CallStack.Count > 0, timeMs
                            ); //Process movement and stuff that is client specific
                    }

                    //Check to see if we should process event commands
                    if (CallStack.Count > 0)
                    {
                        var curStack = CallStack.Peek();
                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Shop && Player.InShop == null)
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Crafting &&
                            Player.CraftingTableId == Guid.Empty)
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Bank && Player.InBank == false)
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Quest &&
                            !Player.QuestOffers.Contains(((StartQuestCommand)curStack.WaitingOnCommand).QuestId))
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        if (curStack.WaitingForResponse == CommandInstance.EventResponse.Timer &&
                            WaitTimer < Globals.Timing.TimeMs)
                        {
                            curStack.WaitingForResponse = CommandInstance.EventResponse.None;
                        }

                        var commandsExecuted = 0;
                        while (curStack.WaitingForResponse == CommandInstance.EventResponse.None &&
                               !PageInstance.ShouldDespawn() &&
                               commandsExecuted < Options.EventWatchdogKillThreshhold)
                        {
                            if (curStack.WaitingForRoute != Guid.Empty)
                            {
                                if (curStack.WaitingForRoute == Player.Id)
                                {
                                    if (Player.MoveRoute == null ||
                                        Player.MoveRoute.Complete && Player.MoveTimer < Globals.Timing.TimeMs)
                                    {
                                        curStack.WaitingForRoute    = Guid.Empty;
                                        curStack.WaitingForRouteMap = Guid.Empty;
                                    }
                                }
                                else
                                {
                                    //Check if the exist exists && if the move route is completed.
                                    foreach (var evt in Player.EventLookup.Values)
                                    {
                                        if (evt.MapId == curStack.WaitingForRouteMap &&
                                            evt.BaseEvent.Id == curStack.WaitingForRoute)
                                        {
                                            if (evt.PageInstance == null)
                                            {
                                                break;
                                            }

                                            if (!evt.PageInstance.MoveRoute.Complete)
                                            {
                                                break;
                                            }

                                            curStack.WaitingForRoute    = Guid.Empty;
                                            curStack.WaitingForRouteMap = Guid.Empty;

                                            break;
                                        }
                                    }
                                }

                                if (curStack.WaitingForRoute != Guid.Empty)
                                {
                                    break;
                                }
                            }
                            else
                            {
                                if (curStack.CommandIndex >= curStack.CommandList.Count)
                                {
                                    CallStack.Pop();
                                }
                                else
                                {
                                    if (WaitTimer < Globals.Timing.TimeMs)
                                    {
                                        CommandProcessing.ProcessCommand(curStack.Command, Player, this);
                                        commandsExecuted++;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                if (CallStack.Count == 0)
                                {
                                    PlayerHasDied = false;

                                    break;
                                }
                            }

                            curStack = CallStack.Peek();
                        }

                        if (commandsExecuted >= Options.EventWatchdogKillThreshhold)
                        {
                            CallStack.Clear(); //Killing this event, we're over it.
                            if (this.BaseEvent.MapId == Guid.Empty)
                            {
                                Log.Error(Strings.Events.watchdogkillcommon.ToString(BaseEvent.Name));
                                if (Player.Power.IsModerator)
                                {
                                    PacketSender.SendChatMsg(
                                        Player, Strings.Events.watchdogkillcommon.ToString(BaseEvent.Name), Color.Red
                                        );
                                }
                            }
                            else
                            {
                                var map = MapInstance.Get(this.BaseEvent.MapId);
                                Log.Error(Strings.Events.watchdogkill.ToString(map.Name, BaseEvent.Name));
                                if (Player.Power.IsModerator)
                                {
                                    PacketSender.SendChatMsg(
                                        Player, Strings.Events.watchdogkill.ToString(map.Name, BaseEvent.Name),
                                        Color.Red
                                        );
                                }
                            }
                        }
                    }
                    else
                    {
                        if (PageInstance.Trigger == EventTrigger.Autorun && WaitTimer < Globals.Timing.TimeMs)
                        {
                            var newStack = new CommandInstance(PageInstance.MyPage);
                            CallStack.Push(newStack);
                        }
                    }
                }
            }

            if (PageInstance == null)
            {
                //Try to Spawn a PageInstance.. if we can
                for (var i = BaseEvent.Pages.Count - 1; i >= 0; i--)
                {
                    if (Conditions.CanSpawnPage(BaseEvent.Pages[i], Player, this))
                    {
                        if (Global)
                        {
                            if (MapInstance.Get(MapId).GetGlobalEventInstance(BaseEvent) != null)
                            {
                                PageInstance = new EventPageInstance(
                                    BaseEvent, BaseEvent.Pages[i], BaseEvent.Id, MapId, this, Player,
                                    MapInstance.Get(MapId).GetGlobalEventInstance(BaseEvent).GlobalPageInstance[i]
                                    );

                                sendLeave = false;
                                PageIndex = i;
                            }
                        }
                        else
                        {
                            PageInstance = new EventPageInstance(BaseEvent, BaseEvent.Pages[i], MapId, this, Player);
                            sendLeave    = false;
                            PageIndex    = i;
                        }

                        break;
                    }
                }

                if (sendLeave && originalPageInstance != null)
                {
                    PacketSender.SendEntityLeaveTo(Player, originalPageInstance);
                }
            }
        }
Example #30
0
 /// <summary>
 /// Gets the PacketDefinition for the PacketId
 /// </summary>
 public static PacketDefinition GetDefinition(PacketId packetId, PacketSender sender)
 {
     return GetDefinition(PacketDefinitions[(uint)packetId.Service], packetId.RawId, sender);
 }
Example #31
0
 public void RemoveStatus()
 {
     mEntity.Statuses.Remove(Spell);
     PacketSender.SendEntityVitals(mEntity);
 }
Example #32
0
 /// <summary>
 /// Gets the PacketDefinition of the given service for the given opcode
 /// </summary>
 public static PacketDefinition GetDefinition(ServiceType service, uint opcode, PacketSender sender)
 {
     return GetDefinition(service, new DirectedPacketId { Sender = sender, OpCode = opcode });
 }
 public SimulationOwnership(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #34
0
 void pnl_RightClicked(Base sender, ClickedEventArgs arguments)
 {
     PacketSender.SendUnequipItem(mYindex);
 }
Example #35
0
 public Crafting(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #36
0
 public PacketDefinition(PacketId[] packetIds, PacketSender sender, List<PacketSegmentStructure> structure)
     : this(packetIds, sender, new ComplexPacketSegmentStructure(null, structure))
 {
 }
Example #37
0
 public Item(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #38
0
 public PacketDefinition(PacketId packetId, PacketSender sender, PacketSegmentStructure structure)
 {
     PacketIds = new[] { packetId };
     Sender = sender;
     Structure = structure ?? new ComplexPacketSegmentStructure();
 }
Example #39
0
 public PacketDefinition(PacketId[] packetIds, PacketSender sender, PacketSegmentStructure structure)
 {
     PacketIds = packetIds;
     Sender = sender;
     Structure = structure ?? new ComplexPacketSegmentStructure();
 }
Example #40
0
		public static ParsedSegment Parse(PacketIn packet, PacketSender sender)
		{
			var parser = new PacketParser(packet, sender);
			parser.Parse();
			return parser.ParsedPacket;
		}
Example #41
0
 public PacketDefinition(PacketId packetId, PacketSender sender, params PacketSegmentStructure[] structure)
     : this(new[] { packetId }, sender, new ComplexPacketSegmentStructure(structure))
 {
 }
        public static void LoadTilesets()
        {
            if (!Directory.Exists("resources/tilesets"))
            {
                Directory.CreateDirectory("resources/tilesets");
            }

            var tilesets               = Directory.GetFiles("resources/tilesets", "*.png");
            var tilesetWarning         = false;
            var suppressTilesetWarning = Preferences.LoadPreference("SuppressTextureWarning");

            if (suppressTilesetWarning != "" && Convert.ToBoolean(suppressTilesetWarning))
            {
                tilesetWarning = true;
            }

            var newTilesets = new List <string>();

            Array.Sort(tilesets, new AlphanumComparatorFast());
            if (tilesets.Length > 0)
            {
                var tilesetBaseList = TilesetBase.Names;
                for (var i = 0; i < tilesets.Length; i++)
                {
                    tilesets[i] = tilesets[i].Replace("resources/tilesets\\", "");
                    if (tilesetBaseList.Length > 0)
                    {
                        for (var x = 0; x < tilesetBaseList.Length; x++)
                        {
                            if (tilesetBaseList[x].ToLower() == tilesets[i].ToLower())
                            {
                                break;
                            }

                            if (x != tilesetBaseList.Length - 1)
                            {
                                continue;
                            }

                            newTilesets.Add(tilesets[i]);
                        }
                    }
                    else
                    {
                        newTilesets.Add(tilesets[i]);
                    }
                }
            }

            sTilesetDict.Clear();
            TilesetTextures.Clear();
            var badTilesets = new List <string>();

            for (var i = 0; i < TilesetBase.Lookup.Count; i++)
            {
                var tileset = TilesetBase.Get(TilesetBase.IdFromList(i));
                if (File.Exists("resources/tilesets/" + tileset.Name))
                {
                    try
                    {
                        sTilesetDict[tileset.Name.ToLower()] = new Texture("resources/tilesets/" + tileset.Name);
                        TilesetTextures.Add(sTilesetDict[tileset.Name.ToLower()]);
                    }
                    catch (Exception exception)
                    {
                        Log.Error($"Fake methods! ({tileset.Name})");
                        if (exception.InnerException != null)
                        {
                            Log.Error(exception.InnerException);
                        }

                        Log.Error(exception);

                        throw;
                    }

                    if (!tilesetWarning)
                    {
                        using (var img = Image.FromFile("resources/tilesets/" + tileset.Name))
                        {
                            if (img.Width > 2048 || img.Height > 2048)
                            {
                                badTilesets.Add(tileset.Name);
                            }
                        }
                    }
                }
            }

            if (badTilesets.Count > 0)
            {
                MessageBox.Show(
                    "One or more tilesets is too large and likely won't load for your players on older machines! We recommmend that no graphic is larger than 2048 pixels in width or height.\n\nFaulting tileset(s): " +
                    string.Join(",", badTilesets.ToArray()), "Large Tileset Warning!", MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation
                    );
            }

            if (newTilesets.Count > 0)
            {
                PacketSender.SendNewTilesets(newTilesets.ToArray());
            }
        }
Example #43
0
 public PacketDefinition(PacketId packetId, PacketSender sender, List<PacketSegmentStructure> structure)
     : this(new[] { packetId }, sender, new ComplexPacketSegmentStructure(null, structure))
 {
 }
Example #44
0
 public Entities(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #45
0
        protected override void ChannelRead0(IChannelHandlerContext context, IByteBuffer input)
        {
            if (_logger.IsTrace)
            {
                _logger.Trace($"Channel read {nameof(NettyHandshakeHandler)} from {context.Channel.RemoteAddress}");
            }

            if (_role == HandshakeRole.Recipient)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"AUTH received from {context.Channel.RemoteAddress}");
                }
                byte[] authData = new byte[input.ReadableBytes];
                input.ReadBytes(authData);
                Packet ack = _service.Ack(_handshake, new Packet(authData));

                //_p2PSession.RemoteNodeId = _remoteId;
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Sending ACK to {RemoteId} @ {context.Channel.RemoteAddress}");
                }
                IByteBuffer buffer = PooledByteBufferAllocator.Default.Buffer();
                buffer.WriteBytes(ack.Data);
                context.WriteAndFlushAsync(buffer);
            }
            else
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Received ACK from {RemoteId} @ {context.Channel.RemoteAddress}");
                }
                byte[] ackData = new byte[input.ReadableBytes];
                input.ReadBytes(ackData);
                _service.Agree(_handshake, new Packet(ackData));
            }

            _initCompletionSource?.SetResult(input);
            _session.Handshake(_handshake.RemoteNodeId);

            FrameCipher       frameCipher  = new FrameCipher(_handshake.Secrets.AesSecret);
            FrameMacProcessor macProcessor = new FrameMacProcessor(_session.RemoteNodeId, _handshake.Secrets);

            if (_role == HandshakeRole.Recipient)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Registering {nameof(LengthFieldBasedFrameDecoder)}  for {RemoteId} @ {context.Channel.RemoteAddress}");
                }
                context.Channel.Pipeline.AddLast("enc-handshake-dec", new LengthFieldBasedFrameDecoder(ByteOrder.BigEndian, ushort.MaxValue, 0, 2, 0, 0, true));
            }
            if (_logger.IsTrace)
            {
                _logger.Trace($"Registering {nameof(ReadTimeoutHandler)} for {RemoteId} @ {context.Channel.RemoteAddress}");
            }
            context.Channel.Pipeline.AddLast(new ReadTimeoutHandler(TimeSpan.FromSeconds(30))); // read timeout instead of session monitoring
            if (_logger.IsTrace)
            {
                _logger.Trace($"Registering {nameof(ZeroFrameDecoder)} for {RemoteId} @ {context.Channel.RemoteAddress}");
            }
            context.Channel.Pipeline.AddLast(new ZeroFrameDecoder(frameCipher, macProcessor, _logManager));
            if (_logger.IsTrace)
            {
                _logger.Trace($"Registering {nameof(ZeroFrameEncoder)} for {RemoteId} @ {context.Channel.RemoteAddress}");
            }
            context.Channel.Pipeline.AddLast(new ZeroFrameEncoder(frameCipher, macProcessor, _logManager));
            if (_logger.IsTrace)
            {
                _logger.Trace($"Registering {nameof(ZeroFrameMerger)} for {RemoteId} @ {context.Channel.RemoteAddress}");
            }
            context.Channel.Pipeline.AddLast(new ZeroFrameMerger(_logManager));
            if (_logger.IsTrace)
            {
                _logger.Trace($"Registering {nameof(ZeroPacketSplitter)} for {RemoteId} @ {context.Channel.RemoteAddress}");
            }
            context.Channel.Pipeline.AddLast(new ZeroPacketSplitter(_logManager));

            PacketSender packetSender = new PacketSender(_serializationService, _logManager);

            if (_logger.IsTrace)
            {
                _logger.Trace($"Registering {nameof(PacketSender)} for {_session.RemoteNodeId} @ {context.Channel.RemoteAddress}");
            }
            context.Channel.Pipeline.AddLast(packetSender);

            if (_logger.IsTrace)
            {
                _logger.Trace($"Registering {nameof(ZeroNettyP2PHandler)} for {RemoteId} @ {context.Channel.RemoteAddress}");
            }
            ZeroNettyP2PHandler handler = new ZeroNettyP2PHandler(_session, _logManager);

            context.Channel.Pipeline.AddLast(_group, handler);

            handler.Init(packetSender, context);

            if (_logger.IsTrace)
            {
                _logger.Trace($"Removing {nameof(NettyHandshakeHandler)}");
            }
            context.Channel.Pipeline.Remove(this);
            if (_logger.IsTrace)
            {
                _logger.Trace($"Removing {nameof(LengthFieldBasedFrameDecoder)}");
            }
            context.Channel.Pipeline.Remove <LengthFieldBasedFrameDecoder>();
        }
Example #46
0
 protected abstract bool Invoke(THandler handler, PacketSender packetSender, IPacket packet);
 void AbandonQuest(object sender, EventArgs e)
 {
     PacketSender.SendAbandonQuest((Guid)((InputBox)sender).UserData);
 }
Example #48
0
 public Power(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #49
0
 public CyclopsBeginSilentRunningProcessor(PacketSender packetSender)
 {
     this.packetSender = packetSender;
 }
Example #50
0
        private object DoAdminActionOnUser(
            Func <Tuple <Client, User> > fetch,
            Func <HttpResponseMessage> onError,
            AdminActions adminAction,
            AdminActionParameters actionParameters
            )
        {
            var(client, user) = fetch();

            if (user == null)
            {
                return(onError());
            }

            var player   = client?.Entity;
            var targetIp = client?.GetIp() ?? "";

            switch (adminAction)
            {
            case AdminActions.Ban:
                if (string.IsNullOrEmpty(Ban.CheckBan(user, "")))
                {
                    Ban.Add(
                        user.Id, actionParameters.Duration, actionParameters.Reason ?? "",
                        actionParameters.Moderator ?? @"api", actionParameters.Ip ? targetIp : ""
                        );

                    client?.Disconnect();
                    PacketSender.SendGlobalMsg(Strings.Account.banned.ToString(user.Name));

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, Strings.Account.banned.ToString(user.Name)
                               ));
                }
                else
                {
                    return(Request.CreateMessageResponse(
                               HttpStatusCode.BadRequest, Strings.Account.alreadybanned.ToString(user.Name)
                               ));
                }

            case AdminActions.UnBan:
                Ban.Remove(user.Id, false);
                PacketSender.SendGlobalMsg(Strings.Account.unbanned.ToString(user.Name));

                return(Request.CreateMessageResponse(
                           HttpStatusCode.OK, Strings.Account.unbanned.ToString(user.Name)
                           ));

            case AdminActions.Mute:
                if (string.IsNullOrEmpty(Mute.FindMuteReason(user.Id, "")))
                {
                    Mute.Add(
                        user, actionParameters.Duration, actionParameters.Reason ?? "",
                        actionParameters.Moderator ?? @"api", actionParameters.Ip ? targetIp : ""
                        );

                    PacketSender.SendGlobalMsg(Strings.Account.muted.ToString(user.Name));

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, Strings.Account.muted.ToString(user.Name)
                               ));
                }
                else
                {
                    return(Request.CreateMessageResponse(
                               HttpStatusCode.BadRequest, Strings.Account.alreadymuted.ToString(user.Name)
                               ));
                }

            case AdminActions.UnMute:
                Mute.Remove(user);
                PacketSender.SendGlobalMsg(Strings.Account.unmuted.ToString(user.Name));

                return(Request.CreateMessageResponse(
                           HttpStatusCode.OK, Strings.Account.unmuted.ToString(user.Name)
                           ));

            case AdminActions.WarpTo:
                if (player != null)
                {
                    var mapId = actionParameters.MapId == Guid.Empty ? player.MapId : actionParameters.MapId;
                    player.Warp(mapId, (byte)player.X, (byte)player.Y);

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, $@"Warped '{player.Name}' to {mapId} ({player.X}, {player.Y})."
                               ));
                }

                break;

            case AdminActions.WarpToLoc:
                if (player != null)
                {
                    var mapId = actionParameters.MapId == Guid.Empty ? player.MapId : actionParameters.MapId;
                    player.Warp(mapId, actionParameters.X, actionParameters.Y, true);

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK,
                               $@"Warped '{player.Name}' to {mapId} ({actionParameters.X}, {actionParameters.Y})."
                               ));
                }

                break;

            case AdminActions.Kick:
                if (client != null)
                {
                    client.Disconnect(actionParameters.Reason);
                    PacketSender.SendGlobalMsg(Strings.Player.serverkicked.ToString(player?.Name));

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, Strings.Player.serverkicked.ToString(player?.Name)
                               ));
                }

                break;

            case AdminActions.Kill:
                if (client != null && client.Entity != null)
                {
                    lock (client.Entity.EntityLock)
                    {
                        client.Entity.Die();
                    }

                    PacketSender.SendGlobalMsg(Strings.Player.serverkilled.ToString(player?.Name));

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, Strings.Commandoutput.killsuccess.ToString(player?.Name)
                               ));
                }

                break;

            case AdminActions.WarpMeTo:
            case AdminActions.WarpToMe:
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, $@"'{adminAction.ToString()}' not supported by the API."
                           ));

            case AdminActions.SetSprite:
            case AdminActions.SetFace:
            case AdminActions.SetAccess:
            default:
                return(Request.CreateErrorResponse(HttpStatusCode.NotImplemented, adminAction.ToString()));
            }

            return(Request.CreateErrorResponse(HttpStatusCode.NotFound, Strings.Player.offline));
        }
 //Trade the item
 void trade_Clicked(Base sender, ClickedEventArgs arguments)
 {
     mTrade.Text = Strings.Trading.pending;
     PacketSender.SendAcceptTrade();
 }
Example #52
0
        private void TryCastSpells()
        {
            // Check if NPC is stunned/sleeping
            if (IsStunnedOrSleeping)
            {
                return;
            }

            //Check if NPC is casting a spell
            if (CastTime > Globals.Timing.TimeMs)
            {
                return; //can't move while casting
            }

            if (CastFreq >= Globals.Timing.TimeMs)
            {
                return;
            }

            // Check if the NPC is able to cast spells
            if (IsUnableToCastSpells)
            {
                return;
            }

            if (Base.Spells == null || Base.Spells.Count <= 0)
            {
                return;
            }

            // Pick a random spell
            var spellIndex = Globals.Rand.Next(0, Spells.Count);
            var spellId    = Base.Spells[spellIndex];
            var spellBase  = SpellBase.Get(spellId);

            if (spellBase == null)
            {
                return;
            }

            if (spellBase.Combat == null)
            {
                Log.Warn($"Combat data missing for {spellBase.Id}.");
            }

            var range          = spellBase.Combat?.CastRange ?? 0;
            var targetType     = spellBase.Combat?.TargetType ?? SpellTargetTypes.Single;
            var projectileBase = spellBase.Combat?.Projectile;

            if (spellBase.SpellType == SpellTypes.CombatSpell &&
                targetType == SpellTargetTypes.Projectile &&
                projectileBase != null &&
                InRangeOf(Target, projectileBase.Range))
            {
                range = projectileBase.Range;
                var dirToEnemy = DirToEnemy(Target);
                if (dirToEnemy != Dir)
                {
                    if (LastRandomMove >= Globals.Timing.TimeMs)
                    {
                        return;
                    }

                    //Face the target -- next frame fire -- then go on with life
                    ChangeDir(dirToEnemy); // Gotta get dir to enemy
                    LastRandomMove = Globals.Timing.TimeMs + Globals.Rand.Next(1000, 3000);

                    return;
                }
            }

            if (spellBase.VitalCost == null)
            {
                return;
            }

            if (spellBase.VitalCost[(int)Vitals.Mana] > GetVital(Vitals.Mana))
            {
                return;
            }

            if (spellBase.VitalCost[(int)Vitals.Health] > GetVital(Vitals.Health))
            {
                return;
            }

            var spell = Spells[spellIndex];

            if (spell == null)
            {
                return;
            }

            if (SpellCooldowns.ContainsKey(spell.SpellId) && SpellCooldowns[spell.SpellId] >= Globals.Timing.RealTimeMs)
            {
                return;
            }

            if (!InRangeOf(Target, range))
            {
                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (targetType)
                {
                case SpellTargetTypes.Self:
                case SpellTargetTypes.AoE:
                    return;
                }
            }

            CastTime = Globals.Timing.TimeMs + spellBase.CastDuration;

            if (spellBase.VitalCost[(int)Vitals.Mana] > 0)
            {
                SubVital(Vitals.Mana, spellBase.VitalCost[(int)Vitals.Mana]);
            }
            else
            {
                AddVital(Vitals.Mana, -spellBase.VitalCost[(int)Vitals.Mana]);
            }

            if (spellBase.VitalCost[(int)Vitals.Health] > 0)
            {
                SubVital(Vitals.Health, spellBase.VitalCost[(int)Vitals.Health]);
            }
            else
            {
                AddVital(Vitals.Health, -spellBase.VitalCost[(int)Vitals.Health]);
            }

            if ((spellBase.Combat?.Friendly ?? false) && spellBase.SpellType != SpellTypes.WarpTo)
            {
                CastTarget = this;
            }
            else
            {
                CastTarget = Target;
            }

            switch (Base.SpellFrequency)
            {
            case 0:
                CastFreq = Globals.Timing.TimeMs + 30000;

                break;

            case 1:
                CastFreq = Globals.Timing.TimeMs + 15000;

                break;

            case 2:
                CastFreq = Globals.Timing.TimeMs + 8000;

                break;

            case 3:
                CastFreq = Globals.Timing.TimeMs + 4000;

                break;

            case 4:
                CastFreq = Globals.Timing.TimeMs + 2000;

                break;
            }

            SpellCastSlot = spellIndex;

            if (spellBase.CastAnimationId != Guid.Empty)
            {
                PacketSender.SendAnimationToProximity(spellBase.CastAnimationId, 1, Id, MapId, 0, 0, (sbyte)Dir);

                //Target Type 1 will be global entity
            }

            PacketSender.SendEntityVitals(this);
            PacketSender.SendEntityCastTime(this, spellId);
        }
Example #53
0
		public static void DumpPacketOut(RealmAccount acc, RealmPacketOut packetOut, PacketSender sender)
		{
			if (CanDump(packetOut.PacketId))
			{
				var writer = GetTextWriter(acc);
				using (var packet = DisposableRealmPacketIn.CreateFromOutPacket(packetOut))
				{
					DumpPacket(packet, sender, false, writer);
				}
			}
		}
Example #54
0
        public void FetchMissingPreviews(bool clearAllFirst)
        {
            var maps = new List <Guid>();

            if (clearAllFirst)
            {
                if (DarkMessageBox.ShowWarning(
                        Strings.MapGrid.clearandfetch, Strings.MapGrid.fetchcaption, DarkDialogButton.YesNo,
                        Properties.Resources.Icon
                        ) !=
                    DialogResult.Yes)
                {
                    return;
                }

                if (DarkMessageBox.ShowInformation(
                        Strings.MapGrid.keepmapcache, Strings.MapGrid.mapcachecaption, DarkDialogButton.YesNo,
                        Properties.Resources.Icon
                        ) ==
                    DialogResult.Yes)
                {
                    Database.GridHideOverlay   = Core.Graphics.HideOverlay;
                    Database.GridHideDarkness  = Core.Graphics.HideDarkness;
                    Database.GridHideFog       = Core.Graphics.HideFog;
                    Database.GridHideResources = Core.Graphics.HideResources;
                    if (Core.Graphics.LightColor != null)
                    {
                        Database.GridLightColor = System.Drawing.Color.FromArgb(
                            Core.Graphics.LightColor.A, Core.Graphics.LightColor.R, Core.Graphics.LightColor.G,
                            Core.Graphics.LightColor.B
                            )
                                                  .ToArgb();
                    }
                    else
                    {
                        Database.GridLightColor = System.Drawing.Color.FromArgb(255, 255, 255, 255).ToArgb();
                    }
                }
                else
                {
                    Database.GridHideOverlay   = true;
                    Database.GridHideDarkness  = true;
                    Database.GridHideFog       = true;
                    Database.GridHideResources = false;
                    Database.GridLightColor    = System.Drawing.Color.White.ToArgb();
                }

                Database.SaveGridOptions();
                Database.ClearAllMapCache();
            }

            //Get a list of maps without images.
            for (var x = 0; x < GridWidth; x++)
            {
                for (var y = 0; y < GridHeight; y++)
                {
                    if (Grid[x, y].MapId != Guid.Empty)
                    {
                        var img = Database.LoadMapCacheLegacy(Grid[x, y].MapId, Grid[x, y].Revision);
                        if (img == null)
                        {
                            maps.Add(Grid[x, y].MapId);
                        }
                        else
                        {
                            img.Dispose();
                        }
                    }
                }
            }

            if (maps.Count > 0)
            {
                if (clearAllFirst ||
                    DarkMessageBox.ShowWarning(
                        Strings.MapGrid.justfetch, Strings.MapGrid.fetchcaption, DarkDialogButton.YesNo,
                        Properties.Resources.Icon
                        ) ==
                    DialogResult.Yes)
                {
                    Globals.FetchingMapPreviews = true;
                    Globals.PreviewProgressForm = new FrmProgress();
                    Globals.PreviewProgressForm.SetTitle(Strings.MapGrid.fetchingmaps);
                    Globals.PreviewProgressForm.SetProgress(
                        Strings.MapGrid.fetchingprogress.ToString(0, maps.Count), 0, false
                        );

                    Globals.FetchCount  = maps.Count;
                    Globals.MapsToFetch = maps;
                    for (var i = 0; i < maps.Count; i++)
                    {
                        PacketSender.SendNeedMap(maps[i]);
                    }

                    Globals.PreviewProgressForm.ShowDialog();
                }
            }
        }
Example #55
0
		public static void DumpPacket(RealmPacketIn packet, PacketSender sender, bool copy, IndentTextWriter writer)
		{
			lock (writer)
			{
				try
				{
					if (copy)
					{
						using (var pkt = packet.Copy())
						{
							PacketAnalyzer.Dump(new ParsablePacketInfo(pkt, sender, DateTime.Now), writer);
						}
					}
					else
					{
						PacketAnalyzer.Dump(new ParsablePacketInfo(packet, sender, DateTime.Now), writer);
					}
				}
				catch (Exception e)
				{
					LogUtil.ErrorException(e, "Unable to parse/render packet " + packet);

					writer.IndentLevel = 0;
					writer.Write(packet.ToHexDump());
				}
			}
		}
Example #56
0
 void Start()
 {
     game = this.GetComponent<Game>();
     handler = this.GetComponent<PacketHandler>();
     sender = this.GetComponent<PacketSender>();
 }